Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Building RESTful APIs with Express.js

1. Introduction

RESTful APIs (Representational State Transfer) are a set of principles for building web services. They use standard HTTP methods like GET, POST, PUT, DELETE, etc., for CRUD operations. Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

2. Setup

2.1 Install Node.js and Express

First, ensure that Node.js is installed on your machine. Then, you can create a new project and install Express.js as follows:

mkdir my-api
cd my-api
npm init -y
npm install express

2.2 Create a Basic Server

Next, set up a basic Express server:

const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;

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

3. Creating Routes

Routes define how your API responds to client requests. Here's how to create basic routes:

app.get('/api/items', (req, res) => {
    res.json({ message: 'Get all items' });
});

app.post('/api/items', (req, res) => {
    res.json({ message: 'Create an item' });
});
Note: Always use appropriate HTTP methods for different operations (GET for fetching data, POST for creating, etc.).

4. Middleware

Middleware functions are functions that have access to the request and response objects. They can modify the request and response objects, end the request-response cycle, and call the next middleware in the stack.

app.use(express.json()); // Parses incoming JSON requests
app.use((req, res, next) => {
    console.log(`${req.method} ${req.url}`);
    next();
});

5. Error Handling

Proper error handling is crucial. You can define a middleware for handling errors:

app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send('Something broke!');
});

6. Testing APIs

Testing your API is essential. You can use tools like Postman or automated testing libraries like Mocha and Chai.

const chai = require('chai');
const chaiHttp = require('chai-http');
const server = require('../server'); // Path to your server file

chai.use(chaiHttp);
chai.request(server)
    .get('/api/items')
    .end((err, res) => {
        chai.expect(res).to.have.status(200);
    });

7. Best Practices

  • Use versioning in your API (e.g. /api/v1/items).
  • Implement authentication and authorization.
  • Document your API using Swagger or Postman.
  • Use environment variables for configuration.
  • Handle errors gracefully and return meaningful messages.

8. FAQ

What is Express.js?

Express.js is a web application framework for Node.js designed for building web applications and APIs. It is known for its simplicity and flexibility.

How do I handle CORS in my API?

You can handle CORS (Cross-Origin Resource Sharing) by using the 'cors' middleware:

const cors = require('cors');
app.use(cors());
What is the difference between REST and GraphQL?

REST is an architectural style using standard HTTP methods, while GraphQL is a query language allowing clients to request only the data they need.