docs/guides/nodejs/pages/creating-a-simple-rest-api.md

95 lines
2.4 KiB
Markdown

---
title: Creating a Simple REST API
description: Creating a simple REST API with NodeJS and Express
published: true
date: 2023-06-28T20:38:30.081Z
tags: nodejs, rest, api, express
editor: markdown
dateCreated: 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
1. 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:
```bash
mkdir nodejs-rest-api
```
2. 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:
```bash
cd nodejs-rest-api
```
3. Next, we need to initialize our project. We can do this by running the following command:
```bash
npm init -y
```
4. Next, we need to install the Express package. We can do this by running the following command:
```bash
npm install express
```
5. Next, we need to create a new file called `index.js`.
6. Next, we need to open the `index.js` file and add the following code:
```javascript
const express = require("express");
const app = express();
```
This will import the Express package and create a new Express application.
7. Next, we need to add the following code to the `index.js` file:
```javascript
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!".
8. Next, we need to add the following code to the `index.js` file:
```javascript
app.listen(3000, () => {
console.log("Server is running on port 3000");
});
```
This will start the server on port 3000.
9. Next, we need to run the following command to start the server:
```bash
node index.js
```
10. Next, we need to open our browser and navigate to `http://localhost:3000/`. We should see the 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.