Skip to content

Adding your own routes to the API

Luca edited this page Jan 11, 2022 · 1 revision

If you do not have an existing REST-API yet, you can save a lot of time and effort by just adding your own routes to this projects API.

Adding a route

This project has its own file system based router, which means that each route has its own .js file located in the routes/ directory. To create a new route, just create a new .js file and copy an existing route as a template (The /status route in status.js is recommended due to its simplicity). In general, a route consists of exported HTTP-verbs containing an object with a preValidation and handler function, just as in a normal Fastify route. You can also create routes in sub-directories, e.g. if you want a my/example/route route, the file path would be routes/my/example/route.js.

Slugs

If you want a "dynamic" route, e.g. /profile/1234 where 1234 is the users ID, you name your file e.g. [userID].js. Then, you are able to access the userID part of the route in your handler in the req.params object, in this case the value will be in req.params.userID.

Adding a database and similar packages

Loading and initiating things like a database is very easy. In the fastify-app.js file, you can just add the setup of these things in the start() method. Make sure to put it between the Init Fastify and the Load and register routes block to make sure the loading order is ideal. A database initialization could look like this:

// At the top of the file
import db from "library/database.js"

// async start() method

// ...

// Below the try...catch block of "Init Fastify":
try {
	await db.init()
	this.fastify.log.info("Database connected and set up")
} catch(err) {
	this.fastify.log.error(`Failed to connect to database:\n${err.stack}`)
}

// ... Load and register routes ...

Clone this wiki locally