- **Epistemic status:** #budding
- **[Source code](https://gitlab.com/Ori6033/what-is-an-api-example)**
We are going to build a basic Node REST API using Express. For this practical exercise, you will need to [install Node.js](https://nodejs.org/en/download/). When you get Node installed, let's get the project started. The following command will initialize the application with a `package.json` that will be responsible for handling dependencies.
```bash
npm init
```
After that, we need Express.js to be able to build our queries easily:
```bash
npm install express --save
```
Create a file called `index.js` and open it up on your text editor of choice. We are going to write our server initialization process with the following code:
```bash
const express = require("express");
const app = express();
app.listen(3000, () => {
console.log("Server running on port 3000 🚀");
});
```
This requires to express into our application, initializes the server, then it listens on port 3000 for requests. Pretty simple setup. Now open up your terminal on the root directory of the application and type the following command:
```
node index.js
```
You should see on the command line `Server running on port 3000 🚀`. What you can do now is open up the `package.json` and on the scripts key add a new line like this:
```
"scripts": {
"server": "node index.js"
}
```
Now every time you need to run the server, you just type `npm run server`. You can type `CTRL + C` to shut down the server. Our server is not doing anything at the moment. Let's send a response every time someone hits this port. On `index.js` add the following at the end of the file:
```
app.get("/", (req, res) => {
res.send("hello world");
});
```
Every time someone hits the base route, this will send hello world back. Type `npm run server` and then go to your browser and type `localhost:3000`. Due to serving the server through our device, using localhost allows us to access servers we are running locally. You should see in your screen `hello world`.
---
## References
- “Express - Node.Js Web Application Framework.” Accessed April 28, 2022. <https://expressjs.com/>.
- Node.js. “Node.Js.” Node.js. Accessed April 28, 2022. <https://nodejs.org/en/>.