In this article I am going to show you how to build a simple API server with hapi and MySQL. I am using Knex as a SQL query builder. And in order to pass the database instance to the request object, I use server decorations property. Rest of the code consists of a simple procedure explained here in detail. To see it in action follow the steps below:
- Setup the project and install dependencies:
1 | mkdir myServer |
- Install dependencies:
1 | npm i @hapi/hapi mysql2 knex |
- Create a file named
server.js
with the contents below:
1 | const hapi = require("@hapi/hapi"); |
Configure and run your MySQL server and modify database instance with proper values(host, user, password, database). If you want to use another SQL database check out the supported clients here and install the one you need.
Run the server with command below:
1 | node server.js |
- Check out the route we defined in our code to see it works:
1 | http://localhost:3000/doesTableExist |
Debugging
If you encounter some errors during development, such as this one:
1 | { |
You could enable debug mode in hapi, which will have your log events printed to the console.
For example, if you want to print any error in a request you would configure your server as follows:
1 | const server = Hapi.server({ debug: { request: ['error'] } }); |