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.tsx9 chars2 lines
Then, install Express.js:
index.tsx20 chars2 lines
Next, create a new file (index.js
for example) that imports and uses Express.js:
index.tsx193 chars11 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.tsx26 chars2 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.tsx154 chars6 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