Shoulder.dev Logo Shoulder.dev

Building a RESTful API with benhall/express-demo

Scenario:

You aim to create a RESTful API using Express and the benhall/express-demo project as a foundation. This API will handle various HTTP methods and use middleware for request validation and response formatting.

Solution:

  1. Familiarize yourself with the project structure: The project consists of several files and directories, including routes, views, and middleware.
  • routes/: Contains Express route files for handling different API endpoints.
  • views/: Contains Handlebars templates for rendering views.
  • public/: Static files (CSS, images) that can be accessed directly.
  • app.js: The main entry point for the Express application.
  • Dockerfile: Used for building Docker images.
  • docker-compose.yml: Configures Docker services.
  • nodemon.json: Configures the development server using nodemon.
  • package.json: Manages project dependencies.
  1. Define routes: Create a new file in the routes directory, e.g., routes/users.js. In this file, define routes for handling user-related API endpoints using Express Router.
const express = require('express');
const router = express.Router();

// Define routes and handlers for each route here

module.exports = router;
  1. Handle HTTP methods: Add routes and their corresponding handlers for each HTTP method (GET, POST, PUT, DELETE). For example, to handle a GET request for retrieving a user, add the following code to the users.js file:
router.get('/users/:id', (req, res) => {
// Your logic for retrieving a user goes here
res.json(user);
});
  1. Use middleware for request validation: Install a middleware package like express-validator for request validation. Add the following code to the app.js file to use it:
const express = require('express');
const bodyParser = require('body-parser');
const expressValidator = require('express-validator');

const app = express();

app.use(bodyParser.json());
app.use(expressValidator());

// Add your routes here

// Middleware for handling validation errors
app.use((err, req, res, next) => {
if (err.isJoi) {
return res.status(400).json({ errors: err.details });
}
next();
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
  1. Use middleware for response formatting: Install a middleware package like express-response for response formatting. Add the following code to the app.js file to use it:
const express = require('express');
const bodyParser = require('body-parser');
const expressValidator = require('express-validator');
const expressResponse = require('express-response');

const app = express();

app.use(bodyParser.json());
app.use(expressValidator());
app.use(expressResponse());

// Add your routes here

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});

Tests:

To verify the API functionality, you can use tools like Postman or REST Assured for testing. Here are some example tests:

  1. Test getting a user:
  • Send a GET request to /api/users/1
  • Verify the response status is 200 OK and the response body contains the user data.
  1. Test creating a new user:
  • Send a POST request to /api/users with a valid user object in the request body
  • Verify the response status is 201 Created and the response body contains the new user data.
  1. Test updating a user:
  • Send a PUT request to /api/users/1 with a valid user object in the request body
  • Verify the response status is 200 OK and the response body contains the updated user data.
  1. Test deleting a user:
  • Send a DELETE request to /api/users/1
  • Verify the response status is 204 No Content.
  1. Test invalid request:
  • Send a request with invalid data (missing required fields, incorrect data types, etc.)
  • Verify the response status is 400 Bad Request and the response body contains error messages.