How to Fetch and Validate Requests with Fastify

overview

Fastify handles requests in handler functions. A request object and a reply object are passed as arguments to the handler function. You use these objects to retrieve data related to requests, generate responses, and so on.

Here, we will explain how to process requests with Fastify using the following versions:

Fastify v4.0.0
nodejs v19.7.0

Also, all the code I’ve created so far is listed below. https://github.com/wiblok/Fastify

How to get request information

Use the request object to get information about the request. A request object stores information about a request from a client. Used within Fastify’s route handlers to access data such as request headers, parameters and payload.

The sample code below is an example for understanding the request object in Fastify. Receive a GET request, access the request headers, query parameters and body data and return a response containing those values.

request.js

const fastify = require("fastify")();

fastify.get("/", async (request, reply) => {
  // get request headers
  const headers = request.headers;

  // get query parameters
  const queryParam = request.query.param;

  // get body data
  const body = request.body;

  const response = {
    headers: headers,
    queryParam: queryParam,
    body: body,
  };

  return response;
});

fastify.listen({ port: 3000 }, (err) => {
  if (err) {
    console.error("Error starting server:", err);
    process.exit(1);
  }
  console.log("Server started on port 3000");
});

Commentary

  • Create a Fastify instance
const fastify = require("fastify")();

Import the Fastify module and create an instance of it.

  • Handling GET requests and retrieving request data:
fastify.get("/", async (request, reply) => {
  // get request headers
  const headers = request.headers;

  // get query parameters
  const queryParam = request.query.param;

  // get body data
  const body = request.body;

  const response = {
    headers: headers,
    queryParam: queryParam,
    body: body,
  };

  return response;
});

Handles GET requests to the path /. When a request comes in, get the request headers, query parameters and body data and return an object containing them as a response.

  • Start server
fastify.listen({ port: 3000 }, (err) => {
  if (err) {
    console.error("Error starting server:", err);
    process.exit(1);
  }
  console.log("Server started on port 3000");
});

Start the server with an instance of Fastify listening on port 3000. If any error occurs, print the error message to the console and terminate the process. If there are no errors, print the message “Server started on port 3000” to the console.

test

curl http://localhost:3000

How to validate request information

Fastify makes it easy for you to validate your requests.

This example validates that the name and age fields are required and age is numeric when a POST request is sent to the /users endpoint.

validate.js

const fastify = require("fastify")();

fastify.post(
  "/users",
  {
    schema: {
      body: {
        type: "object",
        properties: {
          name: { type: "string" },
          age: { type: "number" },
        },
        required: ["name", "age"],
      },
    },
  },
  async (request, reply) => {
    const { name, age } = request.body;

    // What to do if validation succeeds
    reply.send({ message: "User created successfully", name, age });
  }
);

fastify.listen({ port: 3000 }, (err) => {
  if (err) {
    console. error(err);
    process.exit(1);
  }
  console.log("Server is running on port 3000");
});

Commentary

  • Create a Fastify instance
const fastify = require("fastify")();

Import the Fastify module and create an instance of it.

  • POST request handling and request data validation:
fastify.post(
  "/users",
  {
    schema: {
      body: {
        type: "object",
        properties: {
          name: { type: "string" },
          age: { type: "number" },
        },
        required: ["name", "age"],
      },
    },
  },
  async (request, reply) => {
    const { name, age } = request.body;

    // What to do if validation succeeds
    reply.send({ message: "User created successfully", name, age });
  }
);

Handles POST requests to the path /users. When a request comes in, we validate the request body. Validation requires the request body to be an object, the name property to be a string, and the age property to be a number. These properties are required. If the validation succeeds, we will return the user’s name and age as a response along with a success message.

  • Start server
fastify.listen({ port: 3000 }, (err) => {
  if (err) {
    console. error(err);
    process.exit(1);
  }
  console.log("Server is running on port 3000");
});

Start the server with an instance of Fastify listening on port 3000. If any error occurs, print the error message to the console and terminate the process. If there are no errors, print the message “Server is running on port 3000” to the console.

test

# test a successful request
curl -X POST -H "Content-Type: application/json" -d '{"name":"John", "age": 25}' http://localhost:3000/users
# test requests with validation errors
curl -X POST -H "Content-Type: application/json" -d '{"name":"John"}' http://localhost:3000/users

summary

Using the request object allows you to:

By using the request object:

  • You can access request data such as request headers and query parameters.
  • Get data for different parts of the request, such as request path parameters and body data.
  • Obtain authentication and authorization information related to requests, such as authentication tokens and session information.
  • Use middleware functions to validate and transform request data.

The request object allows you to perform various operations on the request’s data. The request object has many properties and methods that allow for a high degree of customization and control.