Build a Simple API with Express
Tags: javascript, express, node, beginners
Published: 2022-12-11 02:55:15

![Rest API Illustration: Shows Multiple Services Connecting to Single API](https://directus-prd-2gwwzglvpa-uc.a.run.app/assets/a40191bd-eed7-49aa-a695-8c8e54c469de)

## What are APIs?

APIs (Application Programming Interfaces) are ways for apps to interact with other apps and services.

Imagine you are making a mobile app that displays a list of movies and you’ve stored all of your movie information in a database or on a server. With an API, you can provide a safe and uniform way for your app to access the movie information from the server.

Today, APIs are widely used to handle various operations and tasks such as payment and authentication. Developers not only create APIs for their projects but also publish their APIs for others to use in their own apps or services. 

## What is a REST API?

REST is a model for building and using APIs over HTTP (the internet)

REST offers some of the following methods for interacting with APIs:

- GET -> used to retrieve the data from a resource 
- POST -> used to submit the data to a resource 
- PUT -> used to replace the data with the targeted resource 
- PATCH ->used to modify a part of a resource  
- DELETE ->used to delete specified resource 

In this three part tutorial, we will build a REST API in NodeJS using the popular ExpressJS framework.

This API will perform some basic CRUD (Create, Read, Update, Delete) operations on a movie list.

For the sake of simplicity we will not use an actual database, but instead will use a local variable (an array) to store our movie data. The concept is all the same though. 

## What is Express?

Express is a NodeJS framework that allows you to easily and quickly stand up web servers.

With Express you can build APIs, serve website content, and more. 

Express is used heavily in the industry and will be a huge tool to have in your tool belt.

## Before You Begin

Make sure you have NodeJS installed on your machine, if you haven't installed it already, you can visit the link below to find the installation guide on the NodeJS official website. (Node 16 is recommended at the time of writing this tutorial)

https://nodejs.org/en/download/

### Setup Your Project

To set up your project, create a blank file called `index.js` (or whatever you want to call it) and place it in a folder on your computer.

### Install Express

Next, let’s add express to your project. Follow the instructions outlined here to install Express: https://expressjs.com/en/starter/installing.html 

TLDR; To install Express quickly:

- Open a terminal, and CD to the directory that contains your `index.js` file
- Run `npm init` to create a new NodeJS project
	- You will be prompted to configure your project, keep all of the defaults for all of the questions
- Run `npm install` express to install Express

At this point, Express should be installed and ready for use

## Start Building your API

As mentioned before, we will build a simple API that updates and reads our movie ‘database’.

Let’s start by going over the basics of how Express works. Below is a sample of a basic Express server - we will go over it line by line.

![Full Code Snippet](https://directus-prd-2gwwzglvpa-uc.a.run.app/assets/a6766558-84a3-4ad4-9b50-dd71ec27a865)

### Lines 1 - 3 | Setup the Express Server

![Code Snippet](https://directus-prd-2gwwzglvpa-uc.a.run.app/assets/2790b442-aaf4-4c38-9880-c20a1d32e33a)

Here we are simply importing Express on line 1.

On line 2, we create a variable called `app` and set it equal to a new instance of Express. This variable will be used to set up and configure our API.

Finally, line 3 we create a variable to store our port number. This will be the port that our API runs on. More on that later.

### Lines 5 - 6 | Let’s Add Some Features to Our Server!

![Code Snippet](https://directus-prd-2gwwzglvpa-uc.a.run.app/assets/89d9c5ec-6303-4fd6-b61c-210556dc80db)

We can add middleware and other extensions to our Express server by calling `app.use()`
Here we are simply adding two extensions built into Express. These extensions help with parsing JSON and URL encoded from data. We do not need to worry about these for right now.

### Lines 8 - 14 | Our Movies Array

![Code Snippet](https://directus-prd-2gwwzglvpa-uc.a.run.app/assets/795bea8b-e3a7-4b40-a803-d8f2e4ee8446)

This will be the variable containing our array of movies. Each movie is simply a string.

### Lines 16 - 18 | The Real Fun! Our First API Route!

![Code Snippet](https://directus-prd-2gwwzglvpa-uc.a.run.app/assets/e64faae6-6a3e-4fa2-bfd9-81706da9c64e)

Now that we have our app object, we can start setting up routes. 

Routes are simply paths to our various API endpoints. You can have as many routes/endpoints as you want! 

Here, we set up a route on line 16 by using `app.get()`. By calling this function, we are setting up a listener that will take any incoming GET requests. 

The path it will listen on is defined by the first argument of the `app.get()` function, so in this example it would be `‘/’` 

The `app.get()` function takes a call back function as the second argument. 

The call back function will fire anytime the route is accessed or requested. This function also receives two objects when fired, req and res.

- **req** is the request object. It contains information about the incoming request and the client that made the request.
- **res** is the response object. It allows you to send a response back to the client that made the request to your API. For instance, you can use the `res.send()` function to send back a string or JSON data.

On line 17 we use `res.send()` to send a response back to our client. We will run this app in the next section so that you can see everything in action.

### Lines 20 - 22 | Tell the Server to Start Listening for Requests!

![Code Snippet](https://directus-prd-2gwwzglvpa-uc.a.run.app/assets/46e64a7c-3cf0-46d0-804f-4b2cd07c7592)

Finally, we will use `app.listen()` to tell our Express app to start listening for requests.

The first argument is the port you want to listen on. In our case, we passed our port variable, which was set to 3000.

The second argument is a callback function to fire once the app has started listening.

## Testing Everything Out

To test all of this out, simply copy the code from this tutorial into your `index.js` file or copy it from this GitHub repo: 
https://github.com/SweetPapa/Simple-Express-API-Tutorial/blob/main/simple-api-example_basic.js 

Once you have the code copied down:
- Open a terminal window and CD into the directory that contains your `index.js` file.
- Run `node index.js` to start the server. 

You should get the following output in your terminal:

```
Example app has started listening on port 3000
```

To immediately see if your API is working, you can open a web browser and navigate to:
http://localhost:3000

> **NOTE:** This works because your browser does a GET request to load webpages. This will not work for other types of requests such as POST, DELETE, etc. For those, we will need to use a tool such as Postman, or use some terminal commands.

To do the same test via a terminal command, try the following:

**For Windows via PowerShell:**
```
$response = Invoke-RestMethod 'http://localhost:3000' -Method 'GET' -Headers $headers
$response | ConvertTo-Json
```

**For macOS, Linux, or CURL:**
```
curl --location --request GET 'http://localhost:3000'
```

You should receive the message that you got in the web browser:

```
Welcome to Our API!
```

### Extra Credit: Let's Use That Movie Data!
> Instead of having the API send back the string 'Welcome to Our API!', try having the API send back the movie data.

## Congratulations, you have set up your first API!

Of course, in a real world example your API would do more than just return a hello world sentence. You could have your API look up data from a database and return that data or perform some sort of other operation.

In the next article, part two, we will add some additional routes and explore some of the other HTTP REST methods (POST, PUT, and DELETE).

Original Post: https://fofocode.dev/article/?post=7