A REST API with NodeJS uses Express to handle HTTP requests and return JSON data. Many beginners forget to set the correct Content-Type header, causing clients to misinterpret the response.
Set Up Your Project
Create a new folder for your API and initialize it with npm. This gives you a package.json file to manage dependencies.
- Open your terminal and run
mkdir node-rest-api && cd node-rest-api - Run
npm init -yto create a default package.json - Install Express with
npm install express
This takes under two minutes and gives you a clean starting point.
Create the Server File
Make a file called server.js in your project folder. This will contain the core logic for your API.
In server.js, import Express, create an app instance, and define a port. The port number 3000 is common for local development.
- Create server.js with
touch server.js(Mac/Linux) ortype nul > server.js(Windows) - Add the following code:
const express = require('express'); const app = express(); const port = 3000; app.get('/', (req, res) => { res.json({ message: 'Hello from your NodeJS REST API' }); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); }); - Save the file
This code sets up a basic server that responds to GET requests at the root URL with a JSON object.
Add Middleware for JSON Handling
To process JSON data in request bodies, you need to add Express’s built-in JSON middleware. Without it, POST and PUT requests with JSON data will not be parsed correctly.
- Add this line below
const app = express();:app.use(express.json());
- Save the file
This middleware runs on every incoming request and parses JSON payloads into JavaScript objects accessible via req.body.
Create a Resource Endpoint
Build a simple endpoint to manage a list of items. This demonstrates how REST APIs handle resources via standard HTTP methods.
- Below the middleware, add an in-memory array to store items:
let items = [ { id: 1, name: 'Learn NodeJS' }, { id: 2, name: 'Build an API' } ]; - Add a GET endpoint to retrieve all items:
app.get('/items', (req, res) => { res.json(items); }); - Add a POST endpoint to create a new item:
app.post('/items', (req, res) => { const newItem = { id: items.length + 1, name: req.body.name }; items.push(newItem); res.status(201).json(newItem); }); - Save the file
Now your API can return a list of items and accept new ones via POST requests with JSON bodies like { "name": "Write documentation" }.
Test Your API
Run your server and test the endpoints using a tool like curl or Thunder Client. This confirms your API behaves as expected.
- Start the server with
node server.js - In another terminal, test the GET endpoint:
curl http://localhost:3000/items
- Test the POST endpoint:
curl -X POST http://localhost:3000/items \ -H "Content-Type: application/json" \ -d '{"name": "Test item"}' - You should see the new item returned with a 201 status
If you get a blank response or error, check that the server is running and the Content-Type header is set correctly.
Common Mistakes and How to Avoid Them
Several issues trip up beginners when building NodeJS REST APIs. Knowing these helps you debug faster and build more reliable APIs.
Forgetting to Set Content-Type
When sending JSON in a POST or PUT request, you must include Content-Type: application/json in the headers. Without it, Express won’t parse the body, and req.body will be undefined.
Always double-check your request headers when testing with curl or a client tool.
Not Handling Errors
Unhandled promise rejections or missing try/catch blocks can crash your server. Wrap async operations in error handling to keep your API running.
For example, if you later add a database, use .catch() or try/catch to return a 500 error instead of crashing.
Using the Wrong Status Codes
Returning 200 for everything confuses clients. Use 201 for created resources, 400 for bad input, and 404 for missing items.
In the POST example above, res.status(201) correctly signals that a new resource was created.
Where It Fits: Choosing Your Approach
Different project needs lead to different API designs. This table helps you decide how to structure your NodeJS REST API based on complexity and goals.
| Factor | Simple Prototype | Real-World App | Team Project |
|---|---|---|---|
| Data Storage | In-memory array | Database (e.g. PostgreSQL) | Database with ORM (e.g. Sequelize) |
| Validation | None or basic checks | Middleware like Joi or express-validator | Centralized validation service |
| Authentication | None | JWT tokens | OAuth 2.0 or SSO |
| Error Handling | Basic try/catch | Custom error classes | Logging and monitoring integrated |
Use this as a rule of thumb: start simple, then add layers only when your project’s needs outgrow the current setup.
Next Steps After Your First Endpoint
Once your basic API works, you’ll want to expand it safely. These steps help you grow your API without introducing bugs or security risks.
- Add validation for incoming data (e.g. ensure
nameis a non-empty string) - Implement PUT and DELETE endpoints to update and remove items
- Connect to a database so data persists between restarts
- Add environment variables for port and database credentials
- Write basic tests for your endpoints using Jest or Vitest
Each step builds on the last, keeping your API maintainable as it grows.