iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
To build a REST-style API with Node.js, define resource routes and HTTP behavior first, then implement those contracts with either the built-in node:http module or a framework such as Express. Validate every request, return status codes that reflect the outcome, and enforce authentication and authorization at the resource level.
How do I build a REST API with Node.js?
Start with the resources clients need to access and the representations they exchange. For a simple widgets API, the collection is /widgets and an individual item is /widgets/{id}. The route and method together describe the operation; the request and response formats, permitted fields, access rules, and errors complete the contract.
| Method and route | Purpose | Example contract |
|---|---|---|
GET /widgets |
Retrieve the collection | Returns a JSON array of widgets. Does not request a state change. |
GET /widgets/{id} |
Retrieve one widget | Returns the matching widget, or an error if it does not exist or the caller cannot access it. |
POST /widgets |
Create a widget | Accepts a documented JSON representation; on creation, returns 201 Created and a Location header identifying the new resource. |
PUT /widgets/{id} |
Replace a widget’s current representation | Accepts the complete representation required by the contract. Define whether a missing resource is created or reported as not found. |
DELETE /widgets/{id} |
Remove a widget | Define whether success returns 204 No Content or another documented response. |
These are conventional choices, not the only possible resource design. Specify which fields each request accepts and which representation a successful response returns. For example, a widget might have a server-assigned identifier and a client-supplied name; document whether unknown fields are rejected and how omitted fields are interpreted.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallOutdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchMatch methods to their HTTP meaning
RFC 9110 defines GET, HEAD, OPTIONS, and TRACE as safe: a client can assume they do not request a state change. Do not make a destructive or otherwise state-changing operation triggerable through GET. The standard defines PUT as replacing all current representations of the target resource with the request content, so do not use it as an undocumented partial update. If the API needs partial changes, define a suitable contract rather than implying replacement semantics.
#1 Best Overall
Retry behavior also depends on the operation. RFC 9110 cautions clients against automatically retrying a non-idempotent request unless they know its semantics are idempotent or can determine the original request was not applied. In particular, do not promise that repeating a POST is safe unless the API provides and documents a mechanism to make that true.
RFC 9110: HTTP Semantics defines the standardized meanings of HTTP methods and their implications for clients.
Should I use node:http or Express?
REST does not require a particular Node.js framework. The built-in HTTP module creates servers and clients and supports streaming, but it is intentionally low level. Node.js parses HTTP messages into headers and bodies; it does not parse the application-specific content in those headers or bodies. As the Node.js documentation puts it, “In order to support the full spectrum of possible HTTP applications, the Node.js HTTP API is very low-level.”
Free tools Windows power users keep installed
One-click scans. No signup required.
Rank #2
| Concern | Built-in node:http |
Express |
|---|---|---|
| Routes | You implement path and method matching. | Register handlers for methods and paths, such as app.get() and app.post(). |
| Request bodies | You read the stream and choose or implement content parsing. | Use middleware appropriate to the request representation; body parsing is not automatic for every format. |
| Middleware and shared behavior | You compose shared behavior yourself. | Provides middleware composition for concerns such as parsing and error handling. |
| Response conventions | You define routing, status, headers, and response behavior. | Route handlers use Express response APIs, but the application still defines its contract and error policy. |
Choose node:http when you need low-level control and are prepared to own the surrounding application behavior. Choose Express if its route and middleware model suits the application. These sources do not establish a universal performance winner; performance depends on the workload and implementation.
A minimal Express route shape
With Express installed and the project configured for its chosen JavaScript module system, a route can express the method-and-path contract directly:
app.get('/widgets/:id', async (req, res, next) => {
try {
const widget = await findWidget(req.params.id);
if (!widget) {
return res.status(404).json({ error: 'not_found' });
}
res.json(widget);
} catch (err) {
next(err);
}
});
This illustrates route shape, not a complete production API. findWidget, authentication, authorization, input constraints, and the final error policy are application responsibilities. Express’s guide documents method-specific routes and middleware: Express routing guide.
Rank #3
How should I validate requests and define representations?
Treat every client-supplied value as untrusted, including route parameters, query parameters, headers, and body fields. Define supported request representations for each operation rather than accepting whatever arrives. For a body-bearing endpoint that expects JSON, check the content type and reject unsupported types with 415 Unsupported Media Type.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
- Check field types and formats, and enforce documented length and range limits.
- Reject unexpected fields when accepting them could create ambiguity or expose unintended behavior.
- Set a maximum request-body size and return
413 Payload Too Largewhen the limit is exceeded. - Validate identifiers and query parameters before using them to select or change resources.
- Return a response content type that matches the representation actually sent; do not simply copy the client’s
Acceptheader.
OWASP’s API Security project recommends validating input type, format, range, and length, rejecting unexpected input, and limiting request size. The precise schema and limits are product-specific and should be part of the API contract.
What HTTP status codes should a REST API use?
Return a status that tells the client what happened. A consistent mapping helps clients distinguish a bad request from missing credentials, denied access, or a server fault.
Rank #4
| Status | Use it when |
|---|---|
201 Created |
A request created a resource; include a Location header when it identifies the new resource. |
400 Bad Request |
The request is malformed or fails basic request validation. |
401 Unauthorized |
Authentication is missing or invalid. The client needs valid credentials. |
403 Forbidden |
The caller is authenticated but is not allowed to perform the operation. |
404 Not Found |
The requested resource does not exist, subject to the API’s documented access and disclosure policy. |
405 Method Not Allowed |
The route does not support the requested method. |
413 Content Too Large |
The request exceeds the endpoint’s body-size limit. |
415 Unsupported Media Type |
The request representation’s media type is not supported for that operation. |
429 Too Many Requests |
The caller has exceeded an applicable rate limit. |
500 Internal Server Error |
An unexpected server failure prevented the request from completing. |
Do not use 404 for every failure or 200 OK for every successful operation. Choose the status and any required headers to match the endpoint’s documented behavior. OWASP’s API Security project discusses these response categories and API error handling.
How should errors work in Express?
Use a stable public error format so clients can handle failures without depending on internal details. For example, an API might consistently return a JSON object with a machine-readable error code and a concise message. Keep stack traces, database messages, and other technical diagnostics in protected server-side logs rather than responses.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Express handles synchronous route errors and documents forwarding rejected promises from async handlers into error handling. Its current guide explains the behavior: Express error handling guide. A centralized error middleware is a useful way to apply the application’s response policy, but it still needs to distinguish expected client errors from unexpected failures. Log enough context for investigation while avoiding secrets and sensitive data.
How do I secure a Node.js API?
Authentication answers who is making a request; authorization determines whether that identity may perform a particular operation on a particular resource. Check both. A valid login or token does not grant permission to every widget or every action.
- Keep passwords, API keys, and tokens out of URL paths and query strings, where URLs may be captured in logs. Put sensitive credentials in appropriate request headers or bodies.
- Authorize access to the specific requested object and operation, not merely to the API in general.
- Restrict management endpoints to the callers and networks that need them.
- Sanitize data written to logs to reduce log-injection risk, and audit security-relevant events without recording credentials.
- Configure cross-origin resource sharing (CORS) for only the origins required by the application.
- Use browser-focused security headers where browser clients benefit from them; they may provide little value for an API consumed only by non-browser clients.
OWASP’s API Security project covers input controls, authentication and authorization, logging, management interfaces, CORS, and security headers. Apply those controls in the context of the actual clients and deployment rather than treating a header or middleware package as a substitute for resource-level access checks.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

