how to make a rest api using the standard library in javascript

Here's an example of how to create a simple REST API using the Node.js built-in http module:

index.tsx
const http = require('http');

const server = http.createServer((request, response) => {
  if (request.method === 'GET' && request.url === '/api/data') {
    // Return some JSON data
    response.setHeader('Content-Type', 'application/json');
    response.statusCode = 200;
    response.end(JSON.stringify({ message: 'Hello, world!' }));
  } else {
    // Return a 404 error for all other requests
    response.statusCode = 404;
    response.end('Not found');
  }
});

// Start the server
server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});
580 chars
20 lines

This creates an HTTP server that listens for requests on port 3000. When a GET request is made to /api/data, the server responds with some JSON data ({ message: 'Hello, world!' }). For all other requests, the server returns a 404 error.

However, using a framework like Express.js can simplify the process of building a REST API. Here's an example using Express:

index.tsx
const express = require('express');

const app = express();
const port = 3000;

// Define a GET route that responds with some JSON data
app.get('/api/data', (req, res) => {
  res.json({ message: 'Hello, world!' });
});

// Start the server
app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}/`);
});
331 chars
15 lines

This code does the same thing as the previous example, but with less boilerplate. Express provides methods for defining routes and handling requests, making it easier to build a REST API.

gistlibby LogSnag