React & REST API: How to get data from a Web Database
Tags: react, javascript, node, tutorial
Published: 2021-03-15 08:02:07

---
published: true
title: React & REST API: How to get data from a Web Database
description: Learn how to call 3rd party REST APIs with authentication from your React App and render the response
series: React & REST API
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yx8i5f4f5pu6vgpgy90z.png
tags: react, javascript, node, tutorial
---

In Part 3 of this series, we'll be making REST API calls from our React project to a web service that needs authentication. In this particular example, we'll be making calls to web databases that are available on the [Kintone](https://www.kintone.com/) platform.

# <u>Prepare a Kintone environment</u>

## What is Kintone?
Kintone is a no-code/low-code cloud platform for teams to quickly & easily share and collaborate on their data.

For developers - Kintone is a really neat platform to create and manage web databases. Databases can be created with drag-and-drop, and can be quickly deployed to be accessed by the GUI, along with opening up APIs to access their data.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kjpgvprsrcgj7q5ovtn6.gif)

Check out the [Kintone Developer Program](https://developer.kintone.io/) for more developer related info.

## Getting my environment
We *could* theoretically swish out our credit card to subscribe for a Kintone pricing plan...but hell no, we're developers. Let's go ahead to get our **free Developer License** by following the instructions [here](https://developer.kintone.io/hc/en-us/articles/220582587). 

That's a free Kintone environment which you can get in 5 minutes, and which you can use for a year, as long as you're using it for developer related projects. Here's a [video version](https://youtu.be/Gzz8SbTuoFg) of getting the environment if you prefer.

## Creating our Kintone App (Database)
Once you have your Kintone environment on-hand, log into it, and navigate to the portal. Follow the article [here](https://get.kintone.help/k/en/user/create_app/tutorial.html) to create a new Kintone App, and [add some records](https://get.kintone.help/k/en/user/using_app/add_record.html) of data into it.

Here's an example of a custom Kintone App I made - it's a simple database of Manga that I really love. The database itself was made in 3 minutes. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w9hsr1ggqw3v05mzpjy4.png)


## Generating an API Token

Follow the tutorial [here](https://developer.kintone.io/hc/en-us/articles/229868687) to generate an API Token for your Kintone App. We'll use this token as an authentication to access data within our Kintone App.

The example in this article will need the "View records" permission for the API Token, but you can adjust these permissions in the App's settings whenever you want. Make sure to click Save, and "Update App" once the API Token has been generated - you won't be able to use the API Token otherwise.

# <u>Update the Backend code</u>

We'll reuse the backend **server.js** code we used in [Part 2](https://dev.to/will_yama/how-to-overcome-cors-errors-2nh9), but with 2 changes:
- Updates to the REST API endpoint
- Addition of headers to the fetch option

## Updating the REST API endpoint

In our example, we'll make a request to get data of multiple records inside the App. For this, we need to make reference to the API we'll be using - in this case, the [Get Records API](https://developer.kintone.io/hc/en-us/articles/360019245194). The endpoint is `https://{subdomain}.kintone.com/k/v1/records.json` so let's go ahead to place that instead of the xkcd endpoint.

```javascript
//const requestEndpoint = "https://xkcd.com/327/info.0.json";
const requestEndpoint = "https://{subdomain}.kintone.com/k/v1/records.json";
```

Replace `{subdomain}` with the unique subdomain that your Kintone platform is running on.

There's one more thing we need to do with the endpoint URL here, which is to add parameters to the end of the string. The only required parameter to add here is the App ID, which is an integer you'll find in the URL when you navigate to your Kintone App.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ame3tydx4ufenqdv6cwi.png)

If your App ID is 1, then add that as a parameter to the end of the URL:

```javascript
const requestEndpoint = "https://{subdomain}.kintone.com/k/v1/records.json?app=1";
```

## Adding headers to the fetch option

If we were to go ahead to make a request to the Kintone endpoint, we'll be returned with an error about not being authorized to access the resource. As we've generated an API Token for authorization, let's go ahead to add this in the header of the request.

```javascript
const fetchOptions = {
    method: 'GET',
    headers:{
        'X-Cybozu-API-Token':'{API_TOKEN}'
    }
}
```

Replace `{API_TOKEN}` with the API Token string generated from your App. Some readers here may be thinking "Wait, is it OK to just paste my API Token in like that...?". Well, the straight answer is "Not really", but we'll go through how to hide our API Token later on, so no worries!

OK, so now our `/getData` Express route should look something like this:

```javascript
app.get('/getData', cors(corsOptions), async (req, res) => {
    const fetchOptions = {
        method: 'GET',
        headers:{
            'X-Cybozu-API-Token':'ChymHTbXx45RcUIBS5y55enlHHHQ0FQ4sk4hrCUY'
        }
    }
    const response = await fetch(requestEndpoint, fetchOptions);
    const jsonResponse = await response.json();
    res.json(jsonResponse);
});
```

Don't worry about my exploited API Token - I'm going to renew it after I create this article.

OK, since we made changes to **server.js**, let's stop the server (`ctrl + c`), save the file, and restart the server. After that, reload the browser showing the React App.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6298vbg6g23l8ldrjcgi.png)

If we see something like this, we've succeeded!
The response should be an object of all (or actually the latest 100) records inside our Kintone App, that include information of values in each field.

## Hide the API token

We have one more step left, which is to hide the API token for better security. It'll be quite a bummer if you decide to share your code openly somewhere only to find that you also shared your API token. 

So here's how. Add `dotenv` to your Express project.

```
npm install dotenv
```

Add this line of code to the beginning of the `server.js` script

```javascript
require('dotenv').config();
```

Create a `.env` file in the same directory as your express app.

```
touch .env
```


Open the `.env` file in the editor, and place in your API token credentials.

```
API_TOKEN = "ChymHTbXx45RcUIBS5y55enlHHHQ0FQ4sk4hrCUY"
```

Make sure to use your own API Token.
Go back to the `server.js` code, and replace the API token string with `process.env.API_TOKEN`.

Update the options

```javascript
    const fetchOptions = {
        method: 'GET',
        headers:{
            'X-Cybozu-API-Token': process.env.API_TOKEN
        }
    }
```

Restart the express server and refresh the React App browser - you should have no problem getting the Kintone App data with this new method!

If the response is stating that you're not using the correct token, you might be using the one I pasted above, which won't be valid for your domain. Make sure to use the API Token that you generated for your own domain and Kintone App.


## The complete code

The `server.js` code should end up looking like this.

```javascript
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const fetch = require('node-fetch');

const PORT = 5000;
const app = express();

app.use(cors());
const corsOptions = {
    origin: "http://localhost:3000"
};

const requestEndpoint = "https://{subdomain}.kintone.com/k/v1/records.json?app=1";

// This function runs if the http://localhost:5000/getData endpoint
// is requested with a GET request
app.get('/getData', cors(corsOptions), async (req, res) => {
    const fetchOptions = {
        method: 'GET',
        headers:{
            'X-Cybozu-API-Token':process.env.API_TOKEN
        }
    }
    const response = await fetch(requestEndpoint, fetchOptions);
    const jsonResponse = await response.json();
    res.json(jsonResponse);
});

app.listen(PORT, () => {
    console.log(`Example app listening at http://localhost:${PORT}`);
});
```

And with that, we've managed to get data from our web database in Kintone, and rendered the contents into our React App's UI. Neat.

# <u>Next steps</u>
In the next part of the series, we'll clean this data a bit more so it'll be more reader friendly.

                       ＿人人人人人人人人人＿
                       ＞ CLEAN IT UP  !＜
                       ￣Y^Y^Y^Y^Y^Y^Y^Y￣
                       (\__/) 
                       (•ㅅ•) 
                       /つ つ