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…
Section overview
5 resourcesRepresentational 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:
- Initialize a new Node.js project by running
npm init -yin the terminal. - Install Express.js by running
npm install express. - Create a new file named
server.jsand 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.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI 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 articleAI 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 articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article