DEV Community

Khalil Habib Shariff
Khalil Habib Shariff

Posted on • Updated on

A Beginner's Guide to Creating a RESTful API with Node.js

Creating a simple API using Node.js is a common use case for the platform, and there are several libraries and frameworks available to make the process easier. Here's a brief overview of how to create a simple API using Node.js.

1.Choose a framework: There are several popular Node.js frameworks for building APIs, such as Express, Hapi, and Koa. For this example, we'll use Express.

2.Install dependencies: Once you've chosen a framework, you'll need to install the necessary dependencies. For Express, you'll need to install the express and body-parser packages. You can do this using the npm package manager:

npm install express body-parser
Enter fullscreen mode Exit fullscreen mode

Create a basic server: Create a new file called server.js, and add the following code:

const express = require('express');
const bodyParser = require('body-parser');

const app = express();

app.use(bodyParser.json());

app.get('/', (req, res) => {
  res.send('Hello, world!');
});

const port = process.env.PORT || 3000;

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

Enter fullscreen mode Exit fullscreen mode

This creates a basic Express server that listens for HTTP requests on port 3000 (or the value of the PORT environment variable, if set). When a GET request is made to the root URL ('/'), the server responds with the string 'Hello, world!'.

4.Add API routes: To create an API, you'll need to define routes that handle different HTTP methods (such as GET, POST, PUT, and DELETE) and perform actions based on the request parameters. For example, to create a route that returns a list of items, you could add the following code:

const items = ['apple', 'banana', 'orange'];

app.get('/items', (req, res) => {
  res.json(items);
});

Enter fullscreen mode Exit fullscreen mode

This defines a new route that listens for GET requests to the '/items' URL. When a request is received, the server responds with a JSON array containing the items array defined earlier.

5.Test the API: You can test the API using a tool like Postman or cURL. For example, to test the '/items' route, you can send a GET request to http://localhost:3000/items. The server should respond with a JSON array containing the items.

Top comments (1)

Collapse
 
olivier_michael profile image
Michael oliver

Simple 💯