API Development / RESTful API

Building your first RESTful API

In this tutorial, you will learn how to build your first RESTful API. We will cover the basics, such as setting up the server, defining resources, and handling requests and respon…

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Representational State Transfer (REST) APIs are architectural style APIs that use HTTP or HTTPS protocol for data communication.


1. Introduction

1.1 Goal of the Tutorial

The goal of this tutorial is to guide you in creating your first RESTful API from scratch. By the end of this tutorial, you will have built a simple API that can perform CRUD (Create, Read, Update, Delete) operations.

1.2 Learning Outcomes

You will learn how to:
- Set up a server using Node.js and Express.js
- Define API resources
- Handle HTTP requests and responses
- Use Postman for testing your API

1.3 Prerequisites

You should have a basic understanding of:
- JavaScript
- Node.js
- Express.js


2. Step-by-Step Guide

2.1 Setting Up the Server

Firstly, we need to set up a server using Node.js and Express.js. Here's how to do it:

  1. Initialize a new Node.js project by running npm init -y in the terminal.
  2. Install Express.js by running npm install express.
  3. Create a new file named server.js and add the following code:
const express = require('express'); // Import Express.js

const app = express(); // Initialize the Express app

const port = 3000; // Define the port

app.listen(port, () => { // Start the server
    console.log(`Server is running on http://localhost:${port}`);
});

2.2 Defining API Resources

To define our API resources, we will create a simple array of objects. Each object will represent a 'user' with properties 'id', 'name', and 'email'. Add the following code to server.js:

let users = [
  { id: 1, name: 'John Doe', email: 'john@example.com' },
  { id: 2, name: 'Jane Doe', email: 'jane@example.com' },
];

3. Code Examples

3.1 Handling HTTP Requests and Responses

3.1.1 GET Request

To handle a GET request, we use the app.get() function. Here's how to return all users:

app.get('/users', (req, res) => { // Define the endpoint
    res.send(users); // Send the users array as a response
});

3.1.2 POST Request

To handle a POST request, we use the app.post() function. Here's how to add a new user:

app.post('/users', (req, res) => { // Define the endpoint
    const newUser = req.body; // Get the new user from the request body
    users.push(newUser); // Add the new user to the users array
    res.send(users); // Send the updated users array as a response
});

4. Summary

In this tutorial, you learned how to:
- Set up a server using Node.js and Express.js
- Define API resources
- Handle HTTP requests and responses

The next step would be to connect your API to a database, such as MongoDB or PostgreSQL. You can learn more about this in the Express.js Database Integration guide.


5. Practice Exercises

5.1 Exercise 1: Return a Single User

Create a GET /users/:id endpoint that returns a single user by ID.

5.2 Exercise 2: Update a User

Create a PUT /users/:id endpoint that updates a user's details.

5.3 Exercise 3: Delete a User

Create a DELETE /users/:id endpoint that removes a user from the array.

5.4 Solutions

You can find the solutions for these exercises in the Express.js Routing Guide.

Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

CSS Minifier & Formatter

Clean and compress CSS files.

Use tool

Random Name Generator

Generate realistic names with customizable options.

Use tool

Scientific Calculator

Perform advanced math operations.

Use tool

Word to PDF Converter

Easily convert Word documents to PDFs.

Use tool

Open Graph Preview Tool

Preview and test Open Graph meta tags for social media.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help