HomeBytesheetsRoadmapsUI TemplatesUI ToolsStack Discussion
3 Topics
Chapter•95 Minutes

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.

Basic HTTP Server
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');
});
💡 The server responds to every request with a JSON payload and listens on port 3000.
Key Takeaways
  • 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.
Knowledge Check

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.

REST Request Flow
Key Takeaways
  • 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.
Knowledge Check

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.

Returning an HTTP Error
res.writeHead(404, {
  'Content-Type': 'application/json'
});

res.end(JSON.stringify({
  error: 'User not found'
}));
💡 The server returns a 404 response with a JSON error body.
Key Takeaways
  • Use status codes consistently and meaningfully.
  • Set Content-Type according to the response representation.
  • Do not use 200 OK for every outcome.
Knowledge Check

Which status code normally means a resource was not found?