Node.js / Node.js Express Framework
Building REST APIs with Express
In this tutorial, you'll learn how to build a RESTful API using Express. This involves creating routes that correspond to the standard HTTP methods and defining the appropriate be…
Section overview
5 resourcesCovers building web applications and REST APIs using the Express framework.
Building REST APIs with Express Tutorial
Introduction
In this tutorial, you will learn how to build a RESTful API using Express. Express is a fast, unopinionated, and minimalist web framework for Node.js, and it's a great tool for creating APIs.
You will learn how to:
- Set up an Express server
- Define routes that correspond to the standard HTTP methods (GET, POST, PUT, DELETE)
- Handle HTTP requests and send responses
- Use middleware for request processing
Prerequisites:
- Basic knowledge of JavaScript
- Node.js and NPM installed on your computer
- Familiarity with HTTP methods would be beneficial
Step-by-Step Guide
-
Setting up Express server
First, we need to install Express. In your project folder, run the following command:
bash npm install express --saveTo set up an Express server, we need to require the
expressmodule and instantiate it.javascript const express = require('express'); const app = express(); -
Defining Routes
Routes are defined using methods of the Express app object that correspond to HTTP methods. For example,
app.get()handles GET requests andapp.post()handles POST requests.javascript app.get('/', function (req, res) { res.send('Hello World!'); });Here, we're defining a route for the root URL ("/") and we're sending 'Hello World!' as a response.
-
Handling Requests and Sending Responses
In the route handler function, Express provides a request object (req) and a response object (res). We can use these to access request data and send responses.
javascript app.get('/users/:id', function (req, res) { const id = req.params.id; res.send(`User ID is: ${id}`); });In this route, we're accessing a URL parameter (id) from the request and sending it in the response.
-
Using Middleware
Middleware functions can perform actions on the request and response objects, or execute any code needed. They can also end the request-response cycle or call the next middleware in the stack.
javascript app.use(function (req, res, next) { console.log('Time:', Date.now()); next(); });This middleware logs the current time for every request.
Code Examples
-
Basic Express Server
Here's a simple Express server that responds to a GET request at the root URL.
```javascript
const express = require('express');
const app = express();
const port = 3000;app.get('/', (req, res) => {
res.send('Hello, World!');
});app.listen(port, () => {
console.log(Server running at http://localhost:${port}/);
});
``` -
Handling Different HTTP Methods
This example shows how to handle different HTTP methods at the same route.
```javascript
app.get('/users', (req, res) => {
res.send('Got a GET request at /users');
});app.post('/users', (req, res) => {
res.send('Got a POST request at /users');
});app.put('/users', (req, res) => {
res.send('Got a PUT request at /users');
});app.delete('/users', (req, res) => {
res.send('Got a DELETE request at /users');
});
```
Summary
In this tutorial, we covered the basics of building a RESTful API using Express. We learned how to set up an Express server, define routes, handle requests and responses, and use middleware.
For further learning, take a deeper look into middleware, learn how to use Express with a database, or explore other Express features.
Practice Exercises
- Create an Express server that responds to a GET request at "/about" with your own message.
- Add a route to your server that accepts POST requests at "/user" and sends a response with the message "Creating a new user".
- Create a middleware that logs the request method and URL for every request to the server.
Solutions:
app.get('/about', (req, res) => {
res.send('This is the about page.');
});
app.post('/user', (req, res) => {
res.send('Creating a new user');
});
app.use((req, res, next) => {
console.log(`Request method: ${req.method}`);
console.log(`Request URL: ${req.url}`);
next();
});
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