Developing APIs quickly and efficiently is essential in today's fast-paced software environment. Fastify, a high-performance web framework for Node.js, combined with TypeScript, offers a powerful toolkit for building robust APIs rapidly. This tutorial guides you through creating a simple REST API using Fastify and TypeScript, emphasizing best practices and speed.

Prerequisites

  • Node.js installed (version 14 or higher)
  • npm or yarn package manager
  • Basic knowledge of JavaScript and TypeScript
  • Code editor (Visual Studio Code recommended)

Setting Up the Project

Create a new directory for your project and initialize it with npm:

mkdir fastify-api

cd fastify-api

npm init -y

Install Fastify and TypeScript along with necessary types:

npm install fastify

npm install --save-dev typescript @types/node @types/fastify

Initialize TypeScript configuration:

npx tsc --init

Configuring TypeScript

Edit tsconfig.json to set the target and module options:

{
  "compilerOptions": {
    "target": "ES2017",
    "module": "CommonJS",
    "outDir": "./dist",
    "strict": true,
    "esModuleInterop": true
  },
  "include": ["src"]
}

Creating the Server

Create a src directory and add server.ts:

import fastify from 'fastify';

const app = fastify({ logger: true });

app.get('/hello', async (request, reply) => {
  return { message: 'Hello, Fastify with TypeScript!' };
});

const start = async () => {
  try {
    await app.listen(3000);
    console.log('Server listening on http://localhost:3000');
  } catch (err) {
    app.log.error(err);
    process.exit(1);
  }
};

start();

Running the API

Compile TypeScript and start the server:

npx tsc

node dist/server.js

Open your browser and navigate to http://localhost:3000/hello. You should see:

{ "message": "Hello, Fastify with TypeScript!" }

Adding More Routes

Extend your server by adding more endpoints. For example, a simple user API:

app.get('/users/:id', async (request, reply) => {
  const { id } = request.params;
  return { userId: id, name: 'User ' + id };
});

Best Practices for Rapid Development

  • Use TypeScript for type safety and better developer experience.
  • Leverage Fastify's plugin system for modular code.
  • Implement validation with schemas to ensure data integrity.
  • Use environment variables for configuration.

Conclusion

Fastify combined with TypeScript provides a streamlined approach to rapid API development. By following this tutorial, you can quickly set up a scalable server, add routes, and ensure code quality. Continue exploring Fastify's plugins and features to build more complex APIs efficiently.