Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Rest API stands for Representational State Transfer Application Programming Interface. It is a set of guidelines and practices for creating and utilizing web services. It's a commonly used architectural approach for creating networked applications, especially web services, which enables internet-based communication across various software programs.
In this blog, we will discuss REST API with Fastify along with its key performance. Let’s start going!
About Fastify
Fastify is a Node.js web framework that offers remarkable speed and performance while preserving a developer-friendly and highly flexible architecture.
Fastify is used for backend development. It is one of the fastest web frameworks running on Node.js. It is one of the primary reasons it is preferable to stay away from node frameworks heavier than others, such as Express and Hapi.
Fastify is the best option for developing RESTful APIs because of its emphasis on performance, modularity, and developer-friendly architecture. With Fastify, you can easily develop RESTful APIs that are effective and high-performing.
Key Performance of Fastify
Some key performances of Fastify are:-
Performance: Fastify is renowned for its outstanding performance benchmarks. It uses contemporary JavaScript technologies and asynchronous programming to manage numerous concurrent connections effectively.
Asynchronous Handling: Fastify was designed from the ground up to handle asynchronous actions, making it easy to grow and process numerous requests without interrupting the event loop.
Schema Validation: Fastify includes built-in JSON schema-based request and response validation support. This improves reliability and reduces situations when errors are likely to occur by ensuring that the data being processed follows the intended structure.
Modularity and Plugins: Through its plugin architecture, Fastify promotes a modular approach to development. Developers can quickly increase the framework's capabilities by adding or developing plugins, encouraging code reuse and maintainability.
Routing: Fastify's simple and flexible route definition tools let developers easily handle many HTTP methods and patterns.
Hooks: Fastify's hooks offer locations in the request/response lifecycle where programmers can include custom functionality. This makes it possible to have precise control over several parts of request processing.
Building Rest API with Fastify
In this section, we will see how to build Rest API with Fstfiy by creating a project and installing all the dependencies in our project.
Installation and Setup
Firstly, create a project and install the Fastify dependencies in our project in order to build a REST API. Before we install the dependencies, download the latest version of Node.js and tool to test the endpoint like PostMan.
To verify the latest version of Node, run the following command.
node -v;
Now, create an empty Node project. To create an empty Node project, run the following command.
npm init -y;
In order to use a fastify framework, import all the necessary dependencies using the following command.
npm i fastify --save
If all the required dependencies are installed, you can verify by seeing the dependencies in “package. json” file.
Creating API Routes
Route definition for APIs is simple with Fastify. To configure your Fastify server and define your API routes, create a file, such as app.js:
JavaScript
JavaScript
// Require the framework and instantiate it const app = require('fastify')({ logger: true })
// Declare a route app.get('/', function (req, reply) { reply.send({ hello: ‘Coding Ninjas’ }) })
// Run the server! app.listen(3000, (err, address) => { if (err) { app.log.error(err) process.exit(1) } app.log.info(`server listening on ${address}`) })
You can also try this code with Online Javascript Compiler
In the above example, the provided code configures a fundamental Fastify server with one routes for dealing with GET requests to get a list of posts. This example shows how to use Fastify to develop a RESTful API.
To run the above code, run the following command.
node app.js
Our server will be operational on the following endpoint once we execute the above command.
Fastify offers a clear and simple approach to developing and handling routes, which are the fundamental building blocks of your online application or API.
Here are the routes that will be defined in our REST API example
GET All Posts: This route fetches a list of all blog posts.
GET Single Post: This route retrieves a specific blog post by its ID.
DELETE Post: This route deletes a blog post by its ID.
PUT Update Post: This route updates an existing blog post by its ID.
POST Create Post: This route creates a new blog post.
Creating Blog Controller
Let's define a controller folder in the project root to keep our code organized. Here, a file called blog.js is created.
To avoid making this tutorial more difficult with database integration, this file contains some sample data. As a result, we employ an array of blog objects, each with a title and ID field.
JavaScript
JavaScript
// Sample blog data let blogs = [ { id: 1, title: 'Coding Ninjas' },
In the above code, there are different handlers that are defined and used to add, update, delete, and get the blog. An array of objects is used to store the object information instead of using the information.
Creating Blog Router
Now, create a route that will allow us to use these controller functions inside of them. We'll use a similar folder structure to develop routes.
Let's make a "routes" directory in the project's root directory. Let's make the "blog.js" file in the "routes" directory.
In the above code, we have defined all the routes that we mentioned above, and also in each of the routes, we have an associated handler that look over the route.
Registering Fastify Routes
We will register Fastify routes to the app object in this step. We load all of the blog routes first. Next, we loop through each route to individually register each one:
JavaScript
JavaScript
const app = require('fastify')({ logger: true })
// Declaring a route app.get('/', function (req, reply) { reply.send({ hello: 'world' }) })
To verify that the blog routes function. Visit http://localhost:3000/blogs/1 to get the first blog from the demo data after starting the server with node index.js. The outcome should be as follows:
Adding Schema Validation to Our Request
Since there were no request validations in the previous code, we may pass anything in the request; therefore, we can utilize the schema key in our routes definition to pass a validation schema to a specific route.
Creating a schema for the route /api/blog/:id will help us initially validate the request parameter and response. The response must contain an object with the properties id (integer) and title (string), with the id argument having to be of type string.
Let's retrieve the blog with ID 3 to check the validity of our validation. Visit http://localhost:3000/api/blog/3 in your browser to start. You should see the subsequent outcome:
{
"id": 3,
"title": "Best Preparation Guide!"
}
If you make some changes to the above code, you can see the error by validation.
Defining Hooks
Using the addHook method, we can define hooks in Fastify. Take a look at the example below, where we'll construct a hook to print every route that has been registered with our REST API.
When we execute the "index.js" file after adding the below code snippet, we will see the output shown below:
Yes, Fastify uses JSON schema validation to guarantee that the data delivered in incoming requests adheres to the desired structure. By confirming that the supplied data follows the prescribed structure, this method improves your API's data integrity and dependability.
Can Fastify handle authentication in REST APIs?
Yes, Fastify can handle REST API authentication. Developers can incorporate authentication methods like JWT (JSON Web Tokens), OAuth, and unique authentication logic thanks to Fastify's adaptable design. This makes it possible to regulate access to your API routes securely and raises the level of security for your application as a whole.
Is Fastify suitable for building RESTful microservices?
Fastify is indeed a good choice for building RESTful microservices. It is the perfect option for creating standalone microservices that must process many requests quickly and efficiently due to its lightweight design and effective architecture.
Conclusion
Fastify focus performance, asynchronous handling, and schema validation to provide reliable APIs and effective data flow. Developers can design high-performance, responsive, and secure applications because to the seamless connection between the front-end and backend that results from React integration.
We hope this blog has helped you to gain knowledge of REST API with Fastify. Do not stop learning! We recommend you read some of our related articles on REST API with Fastify:
But suppose you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. For placement preparations, you must look at the problems, interview experiences, and interview bundles