How to create a backend API in Express JS
Tags: webdev, javascript, programming, tutorial
Published: 2023-11-20 16:39:58


![Image of backend-api process](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/54hrx3c7wc9k8h986w81.png)
To create a backend API in Express JS, we need to do the following steps:

- Install Node JS and Express JS
- Create a project folder and a server file
- Define the data model and the data array
- Create the routes and the handlers for the API
- Test the API with a tool like Postman

## Install Node JS and Express JS

Node JS is a runtime environment that allows you to run JavaScript code outside of a web browser. Express JS is a web framework that provides a set of features and tools for building web applications with Node JS.

To install Node JS, you can download it from the official website and follow the instructions for your operating system. To install Express JS, you can use the Node Package Manager (npm), which is a tool that comes with Node JS and allows you to install and manage various packages and modules for your project. To install Express JS, you can run the following command in your terminal:
```
npm install express
```
This will create a folder called node_modules in your project directory and install Express JS and its dependencies there.

## Create a project folder and a server file

To create a project folder, you can use any name you like, such as express-api. To create a server file, you can use any name you like, such as app.js. This file will contain the code for your backend API. To create the file, you can use any text editor or IDE you prefer, such as Visual Studio Code, Sublime Text, or Atom.

To start the server file, you need to import the express module and create an instance of the express application. You also need to specify a port number for your server to listen to. You can use any port number you like, as long as it is not already in use by another application. For example, you can use port 5000. To do this, you can write the following code in your server file:
```
// Import the express module
const express=require('express');
// Create an instance of the express application
const app=express();
// Specify a port number for the server
const port=5000;
// Start the server and listen to the port
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

```
To run the server, you can use the node command in your terminal, followed by the name of your server file. For example:
```
node app.js
```
This will start the server and print a message in the console. You can stop the server by pressing Ctrl+C in your terminal.

## Define the data model and the data array

To create a backend API, you need to have some data to work with. For this example, we will use a simple data model for a blog post, which has the following properties:

- id: A unique identifier for the post
- title: The title of the post
- content: The content of the post
- author: The name of the author of the post
To store the data, we will use a simple array of objects, which will act as a mock database. You can define the data model and the data array in your server file, as follows:
```
// Define the data function for creating a blog post
function createPost(id, title, content, author) {
  return {
    id: id,
    title: title,
    content: content,
    author: author,
  };
}

// Define the data array for the blog posts
const posts = [
  createPost(1, 'Hello World', 'This is my first blog post', 'Alice'),
  createPost(2, 'Express JS', 'This is a blog post about Express JS', 'Bob'),
  createPost(3, 'RESTful API', 'This is a blog post about RESTful API', 'Charlie'),
];

```

## Create the routes and the handlers for the API

To create the routes and the handlers for the API, you need to use the app object that you created earlier. The app object has methods that correspond to the HTTP methods, such as app.get, app.post, app.put, and app.delete. These methods take two arguments: a path and a callback function. The path is a string that defines the URL for the route, and the callback function is a function that handles the request and sends the response. The callback function has two parameters: req and res. The req object represents the incoming request, and the res object represents the outgoing response.

To create the routes and the handlers for the API, you can write the following code in your server file:

```
// Create a route and a handler for GET /posts
app.get('/posts', (req, res) => {
  // Send the posts array as a JSON response
  res.status(200).json(posts);
});

// Create a route and a handler for GET /posts/:id
app.get('/posts/:id', (req, res) => {
  // Get the id parameter from the request
  const id = req.params.id;

  // Find the post with the given id in the posts array
  const post = posts.find((p) => p.id == id);

  // If the post exists, send it as a JSON response
  if (post) {
    res.json(post);
  } else {
    // If the post does not exist, send a 404 status code and a message
    res.status(404).send('Post not found');
  }
});

// Create a route and a handler for POST /posts
app.post('/posts', (req, res) => {
  // To handle the request body, we need to use a middleware called express.json
  // This middleware parses the request body as JSON and adds it to the req object
  app.use(express.json());

  // Get the data from the request body
  const data = req.body;

  // Validate the data
  if (data.title && data.content && data.author) {
    // If the data is valid, create a new post object with a new id
    const newId = posts.length + 1;
    const newPost = new Post(newId, data.title, data.content, data.author);

    // Add the new post to the posts array
    posts.push(newPost);

    // Send a 201 status code and the new post as a JSON response
    res.status(201).json(newPost);
  } else {
    // If the data is invalid, send a 400 status code and a message
    res.status(400).send('Invalid data');
  }
});

// Create a route and a handler for PUT /posts/:id
app.put('/posts/:id', (req, res) => {
  // To handle the request body, we need to use the express.json middleware
  app.use(express.json());

  // Get the id parameter from the request
  const id = req.params.id;

  // Get the data from the request body
  const data = req.body;

  // Validate the data
  if (data.title && data.content && data.author) {
    // If the data is valid, find the post with the given id in the posts array
    const post = posts.find((p) => p.id == id);

    // If the post exists, update its properties with the data
    if (post) {
      post.title = data.title;
      post.content = data.content;
      post.author = data.author;

      // Send a 200 status code and the updated post as a JSON response
      res.status(200).json(post);
    } else {
      // If the post does not exist, send a 404 status code and a message
      res.status(404).send('Post not found');
    }
  } else {
     res.status(400).send(‘Invalid data’); 
}
```

## Test the API with a tool like Postman

To test the API, you can use a tool like Postman, which is a software that allows you to send and receive HTTP requests and responses. You can download Postman from official website and follow the instructions for your operating system.

To test the API, you need to do the following steps:

- Open Postman and create a new request tab
- Select the HTTP method that matches the route you want to test, such as GET, POST, PUT, or DELETE
- Enter the URL for the route you want to test, such as http://localhost:5000/posts or http://localhost:5000/posts/1
- If the route requires a request body, such as POST or PUT, click on the Body tab and select the raw option and the JSON format
- Enter the data for the request body in JSON format, such as {"title": "New Post", "content": "This is a new post", "author": "Dan"}
- Click on the Send button and see the response in the lower panel
- You can also see the status code, the headers, and the time of the response in the upper panel

You can test different scenarios and see how the API behaves. For example, you can try to create a new post, update an existing post, delete an existing post, get a list of all posts, get a single post, or get a non-existing post. You can also try to send invalid data or invalid URLs and see the error messages.

## Conclusion

In this blog, I have shown you how to create a simple backend API in Express JS that can handle GET and POST requests, and return JSON data. You have learned how to install Node JS and Express JS, how to create a project folder and a server file, how to define the data model and the data array, how to create the routes and the handlers for the API, and how to test the API with a tool like Postman. I hope you have enjoyed this blog and learned something new. If you have any questions or feedback, please leave a comment below. Thank you for reading!