Making A Really Simple Redis API with Node.js
Tags: redis, javascript, node, tutorial
Published: 2020-11-16 16:12:35

## Introduction

Before I sart I would like to mention that this is my first post here at DEV so I'm excited about that. Thank you for reading my post. 

About a week ago I discovered Redis, a simple key-value database that claimed to be the fastest in the world. This claim comes from the fact that it stores the data in memory instead of disk. 

Being a fan of NodeJs and all JavaScript related stuff, the first thing I did was look for a NodeJs driver for Redis. Then I found  [Node Redis](https://redis.js.org)  which was actually recommended in the official Redis website. I spent some time experimenting with it and eventually settled in making a simple API that could save and get items. 

Now I will show you how to make one of your own.

**You can find the finished code in my github at  [this link](https://github.com/dnrm/redis-api) **

---

## Prerequisites

Before getting into the code you should get your Redis database in the cloud. They have an option for a free database for unlimited time.

 [Sign up here](https://redislabs.com/try-free/) 

You should also have NodeJs installed with NPM.

 [Download here](https://nodejs.org/en/download/) 

---

## The Tutorial

We'll start by installing the dependencies:

```js
npm install dotenv redis express
```

Then setting up the .env file with the host, port, and password. You can find this in your Redis dashboard.

#### .env file
```
REDIS_HOST=hostname
REDIS_PORT=port
REDIS_AUTH=password
```

After that I created the index.js file and imported all the dependencies.

#### index.js
```js
require('dotenv').config();
const express = require('express');
const redis = require('redis');
```

Next I created the Express app, the Redis client and set the port where the app would be listening.

#### index.js
```js
const app = express();
const client = redis.createClient({
    port: process.env.REDIS_PORT,
    host: process.env.REDIS_HOST,
});

const port = process.env.PORT || 5050;

client.auth(process.env.REDIS_AUTH, (err, response) => {
    if (err) throw err;
})
```

Now we can start using Express to handle the API calls with the Redis client. What I did was set a **GET** route for the root URL. This route will list all endpoints in the API.

#### index.js
```js
app.get('/', (req, res) => {
    res.status(200).send({
        message: "Looks like you've hit the root url",
        availableurls: [
            "/write/:key/:value",
            "/read/:key"
        ],   
    })
});
```

Then we will make another **GET** route to read from the database. The URL will have a parameter of which key to read from the database.

#### index.js
```js
app.get('/read/:key', (req, res) => {
    client.get(req.params.key, (err, reply) => {
        res.status(200).send({
            data: reply
        });
    });
});
```

Now we just need to make our api be able to write to our database. Similar to our read function, write will take URL parameters. In this case both key and value.

#### index.js
```js
app.get('/write/:key/:value', (req, res) => {
    client.set(req.params.key, req.params.value);
    res.status(200).send({
        status: 'OK'
    });
});
```

Just for fun I will add a 404 route with a fun message. Feel free to sktip this step if you want. **Note: the 404 route should go below all other routes.**

#### index.js
```js
app.get('*', function(req, res){
    res.status(400).send({
        message: "what???",
        status: 404
    });
});
```

For our last step we just need to make our app listen in the specified port and we're done! 

#### index.js
```js
app.listen(port, () => {
    console.log(`App successfully started on http://localhost:${port}`);
});
```



## Conclusion

We now have a working API that can both read and write to a Redis database in the cloud! Isn't that amazing? As mentioned before you can find the full code in my  [github repo](https://github.com/dnrm/redis-api).

---

Thank you very much for reading this post, it really means a lot for me. If you have any feedback, suggestions, or any comment really, feel free to let me know.

Daniel