Learning Backend – Part 2: Building a REST API with Express.js

Learning Backend – Part 2: Building a REST API with Express.js





Learning Backend – Part 2: Building a REST API with Express.js


Prerequisites

1. Installing Express.js

  • In your project directory, install Express using npm:

    npm install express

  • Optionally, install nodemon as a development dependency for automatic server reload:

    npm install --save-dev nodemon

    About nodemon: Nodemon monitors your source code for changes and automatically restarts your server. It adds minimal overhead during development and should be installed as a dev dependency.

    Then, update your package.json scripts to include:

    "start": "node server.js",
    "dev": "nodemon server.js"

2. Creating a Basic Express Server

  • Create a new file named server.js in your project directory (path: my-backend-project/server.js). Add the following content:

    const express = require('express');
    const app = express();
    const port = process.env.PORT || 3000;
    
    // Middleware to parse JSON bodies
    app.use(express.json());
    
    // A simple base route
    app.get('/', (req, res) => {
      res.send('Hello from Express!');
    });
    
    // --- Additional API endpoints will be added here ---
    
    // Start the server
    app.listen(port, () => {
      console.log(`Server is running on port ${port}`);
    });

    Updated Folder Structure:

    my-backend-project/
    ├── .env              (from Part 1)
    ├── index.js          (from Part 1)
    ├── node_modules/
    ├── package-lock.json
    ├── package.json
    └── server.js         (new file)

  • Run your server using:

    node server.js

    Or, if using nodemon:

    npx nodemon server.js

3. Building REST API Endpoints

  • Add new API endpoints in your server.js file after your base route and before the app.listen call.
    For example, insert the following code immediately after your app.get('/', ...) block:

    // GET endpoint for users
    app.get('/users', (req, res) => {
      // Sample users data (replace with database query)
      const users = [
        { id: 1, name: 'Alice' },
        { id: 2, name: 'Bob' }
      ];
      res.json(users);
    });
    
    // POST endpoint to add a new user
    app.post('/users', (req, res) => {
      const newUser = req.body; // In a real app, validate and save this data
      res.status(201).json({ message: 'User created successfully', user: newUser });
    });

    Ensure these endpoint definitions are placed before the app.listen block so that they are registered before the server starts listening for requests.

4. Testing Your API

  • Use a tool like Postman, Insomnia, or curl to test your endpoints. For example, with curl:

    # Test GET endpoint:
    curl http://localhost:3000/users
    
    # Test POST endpoint:
    curl -X POST -H "Content-Type: application/json" -d '{"id":3,"name":"Charlie"}' http://localhost:3000/users

5. Next Steps & Enhancements

  • Add global error-handling middleware to capture and log errors.
  • Integrate your API with the PostgreSQL database from Part 1 to perform real CRUD operations.
  • Implement authentication and authorization for your endpoints.
  • Write tests for your API using frameworks like Mocha, Chai, or Jest.

Join the Conversation

Share your experiences, challenges, and tips with other learners and developers:

  • What endpoints did you build?
  • What challenges did you encounter while creating your API?
  • Do you have recommendations for best practices?

Happy coding! 🚀


This Post Has One Comment

Leave a Reply