Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

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

Posted on • Edited 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 theKintone 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 theKintone Developer Program for more developer related info.

Getting my environment

Wecould 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 ourfree Developer License by following the instructionshere.

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 avideo 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 articlehere to create a new Kintone App, andadd 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 tutorialhere 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 backendserver.js code we used inPart 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, theGet Records API. The endpoint ishttps://{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";constrequestEndpoint="https://{subdomain}.kintone.com/k/v1/records.json";
Enter fullscreen modeExit 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:

constrequestEndpoint="https://{subdomain}.kintone.com/k/v1/records.json?app=1";
Enter fullscreen modeExit 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.

constfetchOptions={method:'GET',headers:{'X-Cybozu-API-Token':'{API_TOKEN}'}}
Enter fullscreen modeExit 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)=>{constfetchOptions={method:'GET',headers:{'X-Cybozu-API-Token':'ChymHTbXx45RcUIBS5y55enlHHHQ0FQ4sk4hrCUY'}}constresponse=awaitfetch(requestEndpoint,fetchOptions);constjsonResponse=awaitresponse.json();res.json(jsonResponse);});
Enter fullscreen modeExit 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 toserver.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. Adddotenv to your Express project.

npm install dotenv
Enter fullscreen modeExit fullscreen mode

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

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

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

touch .env
Enter fullscreen modeExit fullscreen mode

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

API_TOKEN = "ChymHTbXx45RcUIBS5y55enlHHHQ0FQ4sk4hrCUY"
Enter fullscreen modeExit fullscreen mode

Make sure to use your own API Token.
Go back to theserver.js code, and replace the API token string withprocess.env.API_TOKEN.

Update the options

constfetchOptions={method:'GET',headers:{'X-Cybozu-API-Token':process.env.API_TOKEN}}
Enter fullscreen modeExit 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

Theserver.js code should end up looking like this.

require('dotenv').config();constexpress=require('express');constcors=require('cors');constfetch=require('node-fetch');constPORT=5000;constapp=express();app.use(cors());constcorsOptions={origin:"http://localhost:3000"};constrequestEndpoint="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 requestapp.get('/getData',cors(corsOptions),async(req,res)=>{constfetchOptions={method:'GET',headers:{'X-Cybozu-API-Token':process.env.API_TOKEN}}constresponse=awaitfetch(requestEndpoint,fetchOptions);constjsonResponse=awaitresponse.json();res.json(jsonResponse);});app.listen(PORT,()=>{console.log(`Example app listening at http://localhost:${PORT}`);});
Enter fullscreen modeExit 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 modeExit fullscreen mode

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Kintone Developer Advocate working at Cybozu, Japan. A Kintone API preacher, manga lover and a father.
  • Location
    Japan
  • Work
    Kintone Developer Advocate at Cybozu
  • Joined

More fromWilliam Sayama

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp