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:
Prerequisites:
- Basic knowledge of JavaScript
- Node.js and NPM installed on your computer
- Familiarity with HTTP methods would be beneficial
Setting up Express server
First, we need to install Express. In your project folder, run the following command:
bash
npm install express --save
To set up an Express server, we need to require the express
module 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 and app.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.
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');
});
```
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.
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();
});