how to create a rest api in javascript

To create a REST API in Javascript, you can use the Node.js runtime environment and the Express.js framework.

First, you need to install Node.js and initialize a new npm project:

index.tsx
npm init
9 chars
2 lines

Then, install Express.js:

index.tsx
npm install express
20 chars
2 lines

Next, create a new file (index.js for example) that imports and uses Express.js:

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

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(3000, () => {
  console.log('Server listening on port 3000')
})
193 chars
11 lines

The above code creates a server that listens on port 3000 and responds with "Hello World!" to any GET requests to the root endpoint (/).

To add more endpoints and HTTP methods, you can use the following syntax:

index.tsx
app.METHOD(PATH, HANDLER)
26 chars
2 lines

Where METHOD is one of the HTTP methods (GET, POST, PUT, DELETE, etc.), PATH is the endpoint URL path, and HANDLER is a function that handles the HTTP request and response.

For example, to add a new POST endpoint that accepts JSON input, you can do:

index.tsx
app.post('/users', (req, res) => {
  const { name, age } = req.body
  const newUser = createUser(name, age) // some business logic
  res.json(newUser)
})
154 chars
6 lines

This endpoint creates a new user with the given name and age from the JSON input body, using some business logic (createUser function), and responds with the new user data as JSON.

Of course, this is just a basic example. There's much more you can do with Express.js, such as middleware, error handling, database integration, etc.

gistlibby LogSnag