forked from Fascinated/docs
2.4 KiB
2.4 KiB
title | description | published | date | tags | editor | dateCreated |
---|---|---|---|---|---|---|
Creating a Simple REST API | Creating a simple REST API with NodeJS and Express | true | 2023-06-28T20:38:30.081Z | nodejs, rest, api, express | markdown | 2023-06-28T20:38:59.640Z |
Creating a Simple REST API
Introduction
In this guide we will be creating a simple REST API using NodeJS and Express. We will be using the following tools:
- NodeJS
- Express
Prerequisites
- NodeJS installed
- NPM installed
Creating the project
- First we need to create a new directory for our project. You can do this by creating a new folder in your file explorer or by using the following command:
mkdir nodejs-rest-api
- Next, we need to navigate to our new directory. We can do this by opening the folder in our file explorer or by using the following command:
cd nodejs-rest-api
- Next, we need to initialize our project. We can do this by running the following command:
npm init -y
- Next, we need to install the Express package. We can do this by running the following command:
npm install express
-
Next, we need to create a new file called
index.js
. -
Next, we need to open the
index.js
file and add the following code:
const express = require("express");
const app = express();
This will import the Express package and create a new Express application.
- Next, we need to add the following code to the
index.js
file:
app.get("/", (req, res) => {
res
.contentType("application/json")
.send(JSON.stringify({ message: "Hello World!" }));
});
This will create a new route that will return a JSON object with the message "Hello World!".
- Next, we need to add the following code to the
index.js
file:
app.listen(3000, () => {
console.log("Server is running on port 3000");
});
This will start the server on port 3000.
- Next, we need to run the following command to start the server:
node index.js
- Next, we need to open our browser and navigate to
http://localhost:3000/
. We should see the message "{message: "Hello World!"}".
Conclusion
In this guide we created a simple REST API using NodeJS and Express. We created a new directory for our project, initialized our project, installed the Express package, created a new file called index.js
, added the code to the index.js
file, and started the server.