How to Create a Simple API with Express: A Step-by-Step Guide
Building a backend doesn’t have to be complicated. Express, a lightweight Node.js framework, lets you create a fully functional JSON API in minutes. This guide walks you through the essential steps to make a simple API with Express.
Before you begin, make sure Node.js and npm are installed on your machine. Open your terminal, create a project folder, and run npm init -y to generate a package.json file. Then install Express with npm install express.
Step 1: Set Up Your Server
Create an index.js file in your project root. This is where you’ll define your Express app. Write the following setup at the top of the file:
const express = require('express'); const app = express();
You’ll also need to parse incoming JSON. Add app.use(express.json()) to enable middleware that reads request bodies. This is essential for handling POST requests.
Step 2: Define Your Routes
Routes determine how your API responds to requests. For a simple API, you can start with a few key endpoints. Here’s how to build them with the app.get() and app.post() methods.
app.get('/api/ping')— returns a simple “pong” response.app.post('/api/data')— accepts JSON and sends back a confirmation.app.get('/api/users')— returns a small list of sample data.
Each route takes a request and response argument, which you can use to read parameters and send back JSON with res.json().
Step 3: Start and Test the API
To listen for requests, add a final line that starts your server. Using app.listen(3000, () => console.log('API running on port 3000')) will start the server. Run node index.js in your terminal to confirm it works.
Then, open your browser and navigate to http://localhost:3000/api/ping. You should see the JSON response. Alternatively, use a tool like Postman or curl to test your POST endpoint with sample data.
Conclusion
You’ve just built a simple API with Express. From here, you can extend it with a database, authentication, and more complex routing logic to turn it into a full-featured backend.