Apidog

All-in-one Collaborative API Development Platform

API Design

API Documentation

API Debugging

API Mock

API Automated Testing

Sign up for free
Home / Tutorials / Getting Started with Fastify: Building a Simple API

Getting Started with Fastify: Building a Simple API

fastify is a web framework for Node.js that is focused on providing a highly performant and low-overhead solution for building web applications and APIs.

Introduction;

Fastify is a web framework for Node.js that is focused on providing a highly performant and low-overhead solution for building web applications and APIs. It is designed to be simple to use while offering powerful features that make it ideal for a wide range of use cases. Fastify boasts impressive speed benchmarks and is known for its ability to handle high loads efficiently.

Advantages of Fastify:

  • Performance: Fastify is built with a focus on speed, making it one of the fastest web frameworks available for Node.js. Its low overhead and efficient architecture contribute to reduced response times and better overall performance.
  • Schema-based Validation: Fastify provides built-in support for schema-based validation of request and response payloads. This allows developers to define clear expectations for incoming data, leading to improved reliability and security.
  • Extensibility: Fastify is highly extensible, allowing developers to easily add custom plugins and middleware to enhance the functionality of their applications. This makes it adaptable to a wide range of project requirements.
  • Asynchronous Support: Fastify fully embraces asynchronous programming patterns, making it well-suited for handling I/O-bound operations efficiently. It leverages modern JavaScript features like async/await to simplify asynchronous code.
  • Developer-Friendly: With its intuitive API and comprehensive documentation, Fastify aims to provide a developer-friendly experience. It offers clear and concise syntax, making it easy to understand and use for both beginners and experienced developers.

What will be covered in this tutorial:

In this tutorial, we will cover the basics of using Fastify to build a simple API. Starting from setting up a Fastify project, we'll gradually explore its key features, including route handling, request validation, middleware, error handling, testing, and deployment. By the end of the tutorial, you will have a solid understanding of how to use Fastify to create robust and efficient web applications.


Prerequisites

Before we begin, make sure you have the following prerequisites installed:

  1. Node.js and npm: Fastify requires Node.js and npm to be installed on your system. You can download and install them from the official Node.js website.
  2. Basic Knowledge of JavaScript and Node.js: This tutorial assumes that you have a basic understanding of JavaScript and how to work with Node.js. Familiarity with concepts such as callbacks, promises, and modules will be beneficial as we explore Fastify's features.

With these prerequisites in place, you're ready to dive into building with Fastify! Let's get started.


Setting Up Fastify

Installing Fastify via npm

To get started with Fastify, you'll first need to install it via npm, which is the package manager for Node.js. If you're a fan of Yarn or Bun, you can also try to use them. For this guide, I'll use NPM.

And in case you don't know, or fully understand how to use NPM, you can check out this tutorial on how to get your hands dirty with it.

To get started, create a new folder say on your Desktop or your working directory where you'd like to set the Fastify's project.

To do this, simply run the following code on your terminal, step by step following each other

mkdir my-fastify-project
cd my-fastify-project

Now, you've created a folder and moved into that folder from your terminal. Good work!

Next up, initialize npm for that project, and install the Fastify framework.

npm init -y
npm install fastify

At this point, your project consists of only the package.json, package-lock.json, & node_moudles file, which contains metadata about your project and its dependencies. As we continue building our Fastify application, we'll add more files and directories to this structure.

Creating a Simple Server

Setting up a basic Fastify server

Now that we have our project set up, let's create a simple Fastify server. Create a new file called index.js in your project directory and add the following code:

// Import the Fastify module
const fastify = require('fastify')();

// Define a route handler for the root URL
fastify.get('/', async (request, reply) => {
  return { hello: 'world' };
});

// Start the server
const start = async () => {
  try {
    await fastify.listen({ port: 3000 });
    console.log('Server is running on http://localhost:3000');
  } catch (error) {
    console.error('Error starting server:', error);
    process.exit(1);
  }
};

start();

This code sets up a basic Fastify server that listens for incoming HTTP requests on port 3000. When a request is made to the root URL (/), it responds with a JSON object containing the message "hello": "world".

For the following code to work, we need to tell it to run. How can we do so? Well, we can run node index.js on our terminal in the project root folder and it'll work.

But that would mean we'll have to run that command whenever we make a file update. We don't want that stress. We should be able to save the file, and automatically trigger the re-building. How can we do that?
Well, there comes Nodemon.

To install Nodemon, simply run the following code in the terminal;
npm install nodemon --save-dev.
That would install Nodemon and we'll be able to focus on our code and not manually asking it to rebuild.

But we're not done yet with Nodemon. I promise this is the last piece of code that we'll configure for Nodemon. What do we need to do? We need to tell it to automatically trigger whenever we save a file. How do we do this?

Open your package.json file, and replace the script section with the following code:

 "scripts": {
    "start": "node index.js",
    "dev": "nodemon index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

And there we go! We're done with the Nodemon configuration, I promise!

Now to start our server, we need to run npm run dev on our project root directory. Once you're done that, navigate to your browser and type http://localhost:3000/ - you'll see our example response hello world as we defined in our index.js file up above.

A page showing "Hello World" text from server output.

Adding routes to handle different HTTP methods (GET, POST, etc.)

Fastify makes it easy to build REST APIs / define routes for handling different HTTP methods such as GET, POST, PUT, DELETE, etc. Let's add a route to handle a POST request. Update your index.js file with the following code:

// Define a route handler for handling POST requests to '/data'
fastify.post('/data', async (request, reply) => {
  const payload = request.body;
  // Process the incoming data
  // For now, let's just echo back the received data
  return { receivedData: payload };
});

Now, our Fastify server can handle both GET requests to the root URL (/) and POST requests to the /data endpoint.

Responding with JSON data

In both route handlers we've defined ('/' and '/data'), we're responding with JSON data using Fastify's built-in reply methods. Fastify automatically serializes JavaScript objects to JSON, making it easy to send structured data as responses.

With these additions, our Fastify server is now capable of handling basic HTTP requests and responding with JSON data.

But how do we test the POST request? We can't test a POST request from the browser, can we?
To help us, we'll use Apidog.

💡
Apidog is an API management tool that we can use to Design, Debug, Test, Document, Mock, and Build APIs Faster & Together.
button

You can sign up for a free account, try the web interface, or download the desktop app to test your newly created APIs.

To help you understand how to use Apidog, here's a well-written guide. To skip the long talk and reading, you can scan through this section - this is the most important one for us now.

If you followed the guide above, you should be familiar with Apidog to a great extent.

Apidog's page to start a Request

Tap on the request from the project's page, and you'll be able to test the API we created from Fastify's server.

Apidog request page

As you can see from the screenshot above, you'll need to set the HTTP method to POST, enter the right URL( make sure your server is still running), and enter your body payload.

Following the steps above correctly will then give you a 200 response code, and you'll be able to see the response.

If everything works out well for you, you should get the same response as I did.  

Middleware and Plugins

Introduction to Middleware in Fastify

Middleware functions in Fastify are functions that have access to the request and response objects and can perform tasks such as logging, authentication, data parsing, etc., before passing control to the next middleware function or route handler. Middleware functions are executed in the order they are added to the application pipeline.

Creating Custom Middleware Functions

You can create custom middleware functions in Fastify by defining functions that accept the request, reply, and next parameters. Here's an example of a custom logging middleware:

// Custom logging middleware
const loggerMiddleware = async (request, reply, next) => {
  console.log(`[${new Date().toISOString()}] ${request.method} ${request.url}`);
  next();
};

// Register middleware with Fastify
fastify.use(loggerMiddleware);

In this example, the loggerMiddleware function logs the timestamp, HTTP method, and URL of each incoming request. It then calls the next() function to pass control to the next middleware function or route handler.

That's just how Middleware works entirely in Node.js and its other framework such as Express.js.

Installing and Using Fastify Plugins

Fastify provides a rich ecosystem of plugins that extend its functionality for various purposes such as authentication, database integration, validation, etc. You can install and use Fastify plugins via npm. Here's how to install a plugin and register it with Fastify:

npm install fastify-auth fastify-cors

// Import required plugins
const fastifyAuth = require('fastify-auth');
const fastifyCors = require('fastify-cors');

// Register plugins with Fastify
fastify.register(fastifyAuth);
fastify.register(fastifyCors);

In this example, we've installed and registered two plugins: fastify-auth for authentication and fastify-cors for Cross-Origin Resource Sharing (CORS) support.

But hold on. We're not going to test this out. Those are just examples showing how to install and run middleware and plugins in Fastify.

Here's an article to learn more about middleware and plugins. You can do your own research and findings. Just don't get it confused. Middleware in Node.js and Fastify is a wide topic.

Error Handling

Handling Errors in Fastify Routes

In Fastify, you can handle errors in route handlers by throwing errors or returning them from asynchronous functions. Fastify automatically catches these errors and sends an appropriate error response to the client. Here's an example:

// Route handler with error handling
fastify.get('/error', async (request, reply) => {
  // Simulate an error
  throw new Error('Oops! Something went wrong.');
});

From that example, say a user navigates to an /error that doesn't exist or something else, we can throw an error and let the user know what's happening.

If you're curious ( you should be), here's an article to learn more about Errors.

By leveraging middleware, plugins, and error-handling features in Fastify, you can enhance the functionality and reliability of your web applications and APIs. These features allow you to modularize your code, add reusable components, and handle errors gracefully, leading to more maintainable and robust applications.

Conclusion

In this tutorial, we've covered a comprehensive introduction to Fastify, a fast and low-overhead web framework for Node.js. Here's a recap of the key topics we've explored:

  1. Introduction to Fastify: We began by discussing Fastify and its advantages over other Node.js frameworks, including its performance benefits, easy-to-use API, and rich ecosystem of plugins.
  2. Setting Up Fastify: We walked through the process of installing Fastify using npm, initializing a new Fastify project, and exploring the project structure. This set the foundation for building Fastify applications.
  3. Creating a Simple Server: We demonstrated how to set up a basic Fastify server, add routes to handle different HTTP methods, and respond with JSON data. This illustrated the simplicity and flexibility of defining routes and handling requests in Fastify.
  4. Middleware and Plugins: We introduced the concept of middleware in Fastify and showed how to create custom middleware functions. Additionally, we discussed how to extend Fastify's functionality with plugins, installing and using them to add features such as authentication and CORS support.
  5. Error Handling: We covered error handling in Fastify, including how to handle errors in routes, use Fastify's built-in error handling features, and implement custom error handling logic to manage exceptions and provide meaningful error responses to clients.

Through this tutorial, you've gained the knowledge to start building web applications and APIs with Fastify. You've learned about the core features of Fastify, how to handle requests and responses, extend the framework with plugins, and manage errors effectively. With these skills, you're well-equipped to explore more advanced features of Fastify and create efficient, scalable web applications.

As you continue to work with Fastify, remember to explore the extensive documentation and plugin ecosystem available. The Fastify community is active and supportive, offering a wealth of resources to help you advance your skills and build robust applications.

Thank you for following along with this tutorial on Fastify. Happy coding!

Join Apidog's Newsletter

Subscribe to stay updated and receive the latest viewpoints anytime.