DEV Community

Cover image for Build an API in less than 3 minutes
Mitchell Mutandah
Mitchell Mutandah

Posted on

Build an API in less than 3 minutes

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"
},
Enter fullscreen mode Exit fullscreen mode

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}')): '
Enter fullscreen mode Exit fullscreen mode

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

Just like that! #HappyCoding
Cheers

Top comments (0)