Hey folks! In this script I'm going to give you simple steps to build your own API. So without further ado, let's get started!
Download Node.js
We need to set up a Node.js for this purpose, download and install it if you haven't already.
You can download it from it's official website: https://nodejs.org/en/download/
Setup Project
- Create a directory.
- Open it in your preferred code editor.
-
Run the following command in the project terminal to create a package.json:
npm init -y
Adding scripts
Please update the scripts inside the package.json with the following:
"scripts": {
"start": "node index.js"
},
Install Express package
Run the following command in your project terminal to install Express in the project:
npm install express
Creating a route
Create an index.js file. Here we will write an example book route.
//importing packages
const express = require('express');
const app = express();
//adding routes
app.get('/book', (req. res) => {
res.send([
{name: 'Jane Doe', id: 1},
{name: 'Smith Rowe', id: 2},
]);
});
//port
const port = process.env.PORT || 5588;
app.listen(port, () => console.log('Listening on port: ${port}')): '
Code explanation
- First, we have imported Express into our file.
- We create an express app by calling express().
- we created a route /book and attached a function to it. The function will execute when a user makes a GET request to the route.
- Lastly, we run the Express app on a port, in this case, it is port 5500.
Run the API
Run the following command in your project terminal to run the app:
npm start
Test the API
We can use RapidAPI Client, a VS Code extension to make a GET request to the API at the endpoint: https://localhost:5500/book
Top comments (0)