Topics HTTP & Networking Building REST APIs
intermediate 18 min read

Building REST APIs

Design and implement RESTful APIs with proper status codes, headers, and pagination.

REST API Design

const http = require('http');\n\nlet users = [\n  { id: 1, name: 'Alice', email: '[email protected]' },\n  { id: 2, name: 'Bob', email: '[email protected]' },\n];\n\nfunction json(res, status, data) {\n  res.writeHead(status, { 'Content-Type': 'application/json' });\n  res.end(JSON.stringify(data));\n}\n\nconst server = http.createServer((req, res) => {\n  const url = new URL(req.url, `http://${req.headers.host}`);\n  const id = url.pathname.match(/^\/api\/users\/(\d+)$/)?.[1];\n  \n  // GET /api/users\n  if (url.pathname === '/api/users' && req.method === 'GET') {\n    const page = Number(url.searchParams.get('page')) || 1;\n    const limit = Number(url.searchParams.get('limit')) || 10;\n    const start = (page - 1) * limit;\n    json(res, 200, { data: users.slice(start, start + limit), page, limit });\n  \n  // GET /api/users/:id\n  } else if (id && req.method === 'GET') {\n    const user = users.find(u => u.id === Number(id));\n    user ? json(res, 200, user) : json(res, 404, { error: 'User not found' });\n  \n  // POST /api/users\n  } else if (url.pathname === '/api/users' && req.method === 'POST') {\n    let body = '';\n    req.on('data', chunk => body += chunk);\n    req.on('end', () => {\n      const data = JSON.parse(body);\n      const newUser = { id: users.length + 1, ...data };\n      users.push(newUser);\n      json(res, 201, newUser);\n    });\n  } else {\n    json(res, 404, { error: 'Route not found' });\n  }\n});\n\nserver.listen(3000);

Examples

// REST API helper
const http = require('http');

const items = [];
let nextId = 1;

function send(res, status, data) {
  res.writeHead(status, {
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*',
  });
  res.end(JSON.stringify(data));
}

function getBody(req) {
  return new Promise(resolve => {
    let body = '';
    req.on('data', c => body += c);
    req.on('end', () => resolve(JSON.parse(body || '{}')));
  });
}

const server = http.createServer(async (req, res) => {
  const url = new URL(req.url, `http://${req.headers.host}`);
  
  if (url.pathname === '/api/items' && req.method === 'GET') {
    send(res, 200, items);
  } else if (url.pathname === '/api/items' && req.method === 'POST') {
    const body = await getBody(req);
    const item = { id: nextId++, ...body };
    items.push(item);
    send(res, 201, item);
  } else {
    send(res, 404, { error: 'Not found' });
  }
});

server.listen(3000, () => console.log('API running on port 3000'));

Your Notes

Sign in to take notes for this lesson.

Quiz

HTTP & Networking Quiz

0 questions

Sign in to take quiz

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.