Open PortfolioOpen Portfolio.
โ† Back to Blog

Building a REST API with Fastify

June 4, 2026at 2:01 PM UTCBy Pocket Portfolio Teamhow-to
Building a REST API with Fastify
#api#rest#fastify#building

Problem

Building a REST API often requires balancing performance with simplicity. Traditional frameworks can be cumbersome when handling large-scale applications due to their complexity and inefficiencies. Fastify offers a solution by providing a fast and low overhead framework for building APIs, allowing developers to maintain high performance with minimal setup.

Solution with Code

Fastify is a highly efficient web framework for Node.js. It's built for speed and supports asynchronous operations out-of-the-box. Here's how you can build a simple REST API using Fastify:

  1. Install Fastify: Start by initializing your Node.js project and installing Fastify.

    mkdir fastify-api
    cd fastify-api
    npm init -y
    npm install fastify
    
  2. Create a Fastify Server: Set up a basic server in a new file, server.js.

    const fastify = require('fastify')({ logger: true })
    
    // Declare a route
    fastify.get('/api/hello', async (request, reply) => {
      return { message: 'Hello, World!' }
    })
    
    // Run the server!
    const start = async () => {
      try {
        await fastify.listen({ port: 3000 })
        fastify.log.info(`Server listening on ${fastify.server.address().port}`)
      } catch (err) {
        fastify.log.error(err)
        process.exit(1)
      }
    }
    start()
    
  3. Test Your API: You can now run your server and test it by visiting http://localhost:3000/api/hello in your browser or using a tool like curl or Postman.

    node server.js
    

    Navigate to your browser or use a curl command:

    curl http://localhost:3000/api/hello
    

    You should see a JSON response: { "message": "Hello, World!" }.

Key Concepts

  • Performance: Fastify is designed to be one of the fastest web frameworks available. It uses a less than 20ms overhead for handling requests, making it suitable for high-performance applications.

  • Schema Validation: Fastify supports JSON schema validation for your HTTP requests and responses, ensuring data integrity and reducing overhead errors.

  • Asynchronous: Fastify natively supports async/await, which simplifies writing asynchronous code, improving readability and maintainability.

  • Plugins: Fastify's ecosystem includes a wide array of plugins that extend its functionality, such as support for CORS, JWT authentication, and more.

Fastify is an excellent choice for developers looking to build efficient and scalable APIs with minimal setup and maximum performance. By following this guide, you can quickly set up a basic REST API and explore its numerous capabilities to expand your application.

Building a REST API with Fastify | Open Portfolio Blog | Open Portfolio