HTTP Servers and REST APIs
Build HTTP servers using Node.js, understand requests and responses, HTTP methods and status codes, and design RESTful APIs.
Creating an HTTP Server
Node.js provides the built-in node:http module for creating HTTP servers. An HTTP server receives a request and produces a response.
The request contains information such as the HTTP method, URL, headers, and body. The response controls the status code, headers, and response body.
import http from 'node:http';
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Hello Node.js' }));
});
server.listen(3000, () => {
console.log('Server running on port 3000');
});- Node.js can create HTTP servers without Express.
- The request and response objects expose HTTP-level functionality.
- Frameworks such as Express build higher-level abstractions on top of Node HTTP capabilities.
Which built-in Node.js module creates HTTP servers?
REST API Design
REST APIs expose resources through HTTP. Typical methods include GET for retrieval, POST for creation, PUT or PATCH for updates, and DELETE for removal.
Good APIs use meaningful resource names, appropriate status codes, predictable response formats, validation, authentication where required, and consistent error responses.
- Use nouns for resource-oriented URLs such as
/users. - Choose HTTP methods and status codes according to the operation.
- Keep API responses and errors consistent.
Which HTTP method is normally used to retrieve a resource?
Status Codes, Headers, and Content Types
HTTP status codes communicate the result of a request. 2xx indicates success, 3xx redirection, 4xx client-side problems, and 5xx server-side failures.
Headers provide metadata about the request and response. Common headers include Content-Type, Authorization, Cache-Control, Accept, and security-related headers.
res.writeHead(404, {
'Content-Type': 'application/json'
});
res.end(JSON.stringify({
error: 'User not found'
}));- Use status codes consistently and meaningfully.
- Set
Content-Typeaccording to the response representation. - Do not use
200 OKfor every outcome.
Which status code normally means a resource was not found?