Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

REST API Tutorial

Introduction to REST API

REST (Representational State Transfer) is an architectural style for designing networked applications. It relies on a stateless, client-server, cacheable communications protocol -- the HTTP. REST is often used in the development of web services.

Key Concepts of REST

Before diving into the implementation, it is important to understand the key concepts of REST:

  • Resource: Any piece of information that can be named and manipulated. Examples include users, posts, and comments.
  • Endpoint: A specific URL where a resource can be accessed. For example, /users might be an endpoint for accessing user information.
  • HTTP Methods: The actions that can be performed on the resources. Common methods include GET, POST, PUT, DELETE.
  • Statelessness: Each request from client to server must contain all the information needed to understand and process the request. No client context is stored on the server between requests.
  • Representation: The format in which resources are transported. Common formats include JSON, XML.

Creating a Simple REST API with Node.js and Express

In this section, we will create a simple REST API using Node.js and Express. The API will manage a list of users.

Step 1: Setting Up the Project

First, create a new directory for your project and initialize it with npm:

mkdir rest-api-tutorial
cd rest-api-tutorial
npm init -y

Next, install Express:

npm install express

Step 2: Creating the Server

Create a new file named server.js and add the following code to set up the server:

const express = require('express');
const app = express();
const port = 3000;

app.use(express.json());

app.get('/', (req, res) => {
    res.send('Hello World!');
});

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

Run the server using the following command:

node server.js

You should see the message "Server is running on http://localhost:3000" in your terminal.

Step 3: Creating the User Routes

Now, we will create routes to manage the users. Add the following code to server.js:

const users = [];

app.get('/users', (req, res) => {
    res.json(users);
});

app.post('/users', (req, res) => {
    const user = req.body;
    users.push(user);
    res.status(201).json(user);
});

app.get('/users/:id', (req, res) => {
    const user = users.find(u => u.id === parseInt(req.params.id));
    if (!user) return res.status(404).send('User not found');
    res.json(user);
});

app.put('/users/:id', (req, res) => {
    const user = users.find(u => u.id === parseInt(req.params.id));
    if (!user) return res.status(404).send('User not found');
    Object.assign(user, req.body);
    res.json(user);
});

app.delete('/users/:id', (req, res) => {
    const index = users.findIndex(u => u.id === parseInt(req.params.id));
    if (index === -1) return res.status(404).send('User not found');
    users.splice(index, 1);
    res.status(204).send();
});
                

With this code, we have created the following endpoints:

  • GET /users - Retrieve all users
  • POST /users - Create a new user
  • GET /users/:id - Retrieve a user by ID
  • PUT /users/:id - Update a user by ID
  • DELETE /users/:id - Delete a user by ID

Testing the API with Postman

To test the API, you can use Postman or any other API testing tool. Here are some example requests:

1. Create a User

Send a POST request to http://localhost:3000/users with the following JSON body:

{
    "id": 1,
    "name": "John Doe",
    "email": "john.doe@example.com"
}
                

2. Retrieve All Users

Send a GET request to http://localhost:3000/users.

3. Retrieve a User by ID

Send a GET request to http://localhost:3000/users/1.

4. Update a User

Send a PUT request to http://localhost:3000/users/1 with the following JSON body:

{
    "name": "Jane Doe",
    "email": "jane.doe@example.com"
}
                

5. Delete a User

Send a DELETE request to http://localhost:3000/users/1.

Conclusion

In this tutorial, we have covered the basics of REST APIs, discussed key concepts, and implemented a simple REST API using Node.js and Express. We also demonstrated how to test the API using Postman. With this knowledge, you can start building your own RESTful services for various applications.