Building a Simple REST API with NodeJS & Fastify
Tags: node, restapi, fastify, webdev
Published: 2023-05-01 11:27:20

Are you planning to use NodeJS to create a REST API? In this blog post, we'll demonstrate how to create a straightforward REST API using Fastify, a well-liked and compact web framework for NodeJS. Fastify is a fantastic option for creating APIs because it is built for speed and effectiveness.

In this tutorial, we'll cover the following topics:

**1. Setting up the project**
**2. Building the API**
**3. Adding more routes**
**4. Testing the API**
**5. Conclusion**

So, let's dive in!

## 1. Setting up the project

Making a new project directory and initialising it with npm is the first step. Run the following commands after opening your terminal:

```
mkdir fastify-api
cd fastify-api
npm init -y

```

This will create a new directory called **fastify-api** and initialize it with a **package.json** file.

Installing Fastify and its dependencies comes next. To install Fastify, execute the following command:

```
npm install fastify

```

## 2. Building the API

After setting up the project and installing Fastify, we can now begin creating our API. Let's begin by creating a new file called index.js in the project directory's root.

```
const fastify = require('fastify')();

fastify.get('/', async (request, reply) => {
  return { message: 'Hello, World!' };
});

fastify.listen(3000, (err, address) => {
  if (err) {
    console.error(err);
    process.exit(1);
  }
  console.log(`Server listening on ${address}`);
});

```
In this case, Fastify was imported and a new instance was made of it. Then, we created a route that responds to GET requests for our API's root. A JSON object containing the message "Hello, World!" is returned by the route handler.

Finally, we used the **listen()** method to launch the server on port 3000. We record errors to the console and stop the process if one occurs. In the absence of such, we log the server's listening IP.

## 3. Adding more routes

Let's add more routes now that our fundamental API is operational. As an illustration, let's implement a route that responds to POST requests to the **/api/users** endpoint and returns a JSON object containing the user's name and email.

```
fastify.post('/api/users', async (request, reply) => {
  const { name, email } = request.body;
  return { name, email };
});

```

In this instance, a new route was built to handle POST requests to the **/api/users** URL. The **name** and **email** properties are extracted from the request body by the route handler using destructuring, and it then returns a JSON object with those properties.

## 4. Testing the API

We can use a tool  like **Postman** or **curl** to test our API. Here, we'll use **curl** as an example.

Start the server by running the command:

```
node index.js

```

Then, open a new terminal window and run the following command to send a GET request to the root of our API:

```
curl http://localhost:3000/

```

This should return a JSON object with the message "Hello, World!".

Next, let's send a POST request to our /api/users endpoint. Run the following command:

```
curl -X POST -H "Content-Type: application/json" -d '{"name":"John Doe","email":"john

```


## 5. Conclusion

In this article, we demonstrated how to use Fastify and NodeJS to create a straightforward REST API. We went over the fundamentals of starting a project, creating routes, and using curl to test the API.

Of course, this is only the beginning. Fastify can be used to create more intricate APIs with extra capabilities like database integration and authentication.

We hope that this guide helped you get started creating your own REST API using Fastify and NodeJS. Coding is fun!