DEV Community

Cover image for React & REST API: How to get data from a Web Database
William Sayama
William Sayama

Posted on • Updated on

React & REST API: How to get data from a Web Database

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 platform.

Prepare a Kintone environment

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

Check out the Kintone Developer Program 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.

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 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 to create a new Kintone App, and add some records 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

Generating an API Token

Follow the tutorial here 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.

Update the Backend code

We'll reuse the backend server.js code we used in Part 2, 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. The endpoint is https://{subdomain}.kintone.com/k/v1/records.json so let's go ahead to place that instead of the xkcd endpoint.

//const requestEndpoint = "https://xkcd.com/327/info.0.json";
const requestEndpoint = "https://{subdomain}.kintone.com/k/v1/records.json";
Enter fullscreen mode Exit fullscreen mode

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

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

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

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.

const fetchOptions = {
    method: 'GET',
    headers:{
        'X-Cybozu-API-Token':'{API_TOKEN}'
    }
}
Enter fullscreen mode Exit fullscreen mode

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:

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);
});
Enter fullscreen mode Exit fullscreen mode

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

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
Enter fullscreen mode Exit fullscreen mode

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

require('dotenv').config();
Enter fullscreen mode Exit fullscreen mode

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

touch .env
Enter fullscreen mode Exit fullscreen mode

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

API_TOKEN = "ChymHTbXx45RcUIBS5y55enlHHHQ0FQ4sk4hrCUY"
Enter fullscreen mode Exit fullscreen mode

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

    const fetchOptions = {
        method: 'GET',
        headers:{
            'X-Cybozu-API-Token': process.env.API_TOKEN
        }
    }
Enter fullscreen mode Exit fullscreen mode

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.

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}`);
});
Enter fullscreen mode Exit fullscreen mode

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.

Next steps

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 ̄
                   (\__/) 
                   (•ㅅ•) 
                   /つ つ
Enter fullscreen mode Exit fullscreen mode

Top comments (0)