| title | Use the OpenAPI Specification of a Data App with Next.js |
|---|---|
| summary | Learn how to use the OpenAPI Specification of a Data App to generate client code and develop a Next.js application. |
This document introduces how to use the OpenAPI Specification of a Data App to generate client code and develop a Next.js application.
Before using OpenAPI Specification with Next.js, make sure that you have the following:
- A TiDB cluster. For more information, see Create a {{{ .starter }}} or Essential Cluster or Create a TiDB Cloud Dedicated cluster.
- Node.js
- npm
- yarn
This document uses a {{{ .starter }}} cluster as an example.
To begin with, create a table test.repository in your TiDB cluster and insert some sample data into it. The following example inserts some open source projects developed by PingCAP as data for demonstration purposes.
To execute the SQL statements, you can use SQL Editor in the TiDB Cloud console.
-- Select the database
USE test;
-- Create the table
CREATE TABLE repository (
id int NOT NULL PRIMARY KEY AUTO_INCREMENT,
name varchar(64) NOT NULL,
url varchar(256) NOT NULL
);
-- Insert some sample data into the table
INSERT INTO repository (name, url)
VALUES ('tidb', 'https://github.com/pingcap/tidb'),
('tikv', 'https://github.com/tikv/tikv'),
('pd', 'https://github.com/tikv/pd'),
('tiflash', 'https://github.com/pingcap/tiflash');After the data is inserted, navigate to the Data Service page in the TiDB Cloud console. Create a Data App that links to your TiDB cluster, create an API key for the Data App, and then create a GET /repositories endpoint in the Data App. The corresponding SQL statement for this endpoint is as follows, which fetches all rows from the test.repository table:
SELECT * FROM test.repository;For more information, see Get started with Data Service.
The following uses Next.js as an example to demonstrate how to generate client code using the OpenAPI Specification of a Data App.
-
Create a Next.js project named
hello-repos.To create a Next.js project using the official template, use the following command and keep all the default options when prompted:
yarn create next-app hello-repos
Change the directory to the newly created project using the following command:
cd hello-repos -
Install dependencies.
This document uses OpenAPI Generator to automatically generate API client libraries from the OpenAPI Specification.
To install OpenAPI Generator as a development dependency, run the following command:
yarn add @openapitools/openapi-generator-cli --dev
-
Download the OpenAPI Specification and save it as
oas/doc.json.- On the TiDB Cloud Data Service page, click your Data App name in the left pane to view the App settings.
- In the API Specification area, click Download, select the JSON format, and then click Authorize if prompted.
- Save the downloaded file as
oas/doc.jsonin thehello-reposproject directory.
For more information, see Download the OpenAPI Specification.
The structure of the
oas/doc.jsonfile is as follows:{ "openapi": "3.0.3", "components": { "schemas": { "getRepositoriesResponse": { "properties": { "data": { "properties": { "columns": { ... }, "result": { ... }, "rows": { "items": { "properties": { "id": { "type": "string" }, "name": { "type": "string" }, "url": { "type": "string" } ... "paths": { "/repositories": { "get": { "operationId": "getRepositories", "responses": { "200": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/getRepositoriesResponse" } } }, "description": "OK" }, ... -
Generate the client code:
yarn run openapi-generator-cli generate -i oas/doc.json --generator-name typescript-fetch -o gen/api
This command generates the client code using the
oas/doc.jsonspecification as input and outputs the client code to thegen/apidirectory.
You can use the generated client code to develop your Next.js application.
-
In the
hello-reposproject directory, create a.env.localfile with the following variables, and then set the variable values to the public key and private key of your Data App.TIDBCLOUD_DATA_SERVICE_PUBLIC_KEY=YOUR_PUBLIC_KEY TIDBCLOUD_DATA_SERVICE_PRIVATE_KEY=YOUR_PRIVATE_KEYTo create an API key for a Data App, see Create an API key.
-
In the
hello-reposproject directory, replace the content ofapp/page.tsxwith the following code, which fetches data from theGET /repositoriesendpoint and renders it:import {DefaultApi, Configuration} from "../gen/api" export default async function Home() { const config = new Configuration({ username: process.env.TIDBCLOUD_DATA_SERVICE_PUBLIC_KEY, password: process.env.TIDBCLOUD_DATA_SERVICE_PRIVATE_KEY, }); const apiClient = new DefaultApi(config); const resp = await apiClient.getRepositories(); return ( <main className="flex min-h-screen flex-col items-center justify-between p-24"> <ul className="font-mono text-2xl"> {resp.data.rows.map((repo) => ( <a href={repo.url}> <li key={repo.id}>{repo.name}</li> </a> ))} </ul> </main> ) }
Note:
If the linked clusters of your Data App are hosted in different regions, you will see multiple items in the
serverssection of the downloaded OpenAPI Specification file. In this case, you also need to configure the endpoint path in theconfigobject as follows:const config = new Configuration({ username: process.env.TIDBCLOUD_DATA_SERVICE_PUBLIC_KEY, password: process.env.TIDBCLOUD_DATA_SERVICE_PRIVATE_KEY, basePath: "https://${YOUR_REGION}.data.dev.tidbcloud.com/api/v1beta/app/${YOUR_DATA_APP_ID}/endpoint" });
Make sure to replace
basePathwith the actual endpoint path of your Data App. To get${YOUR_REGION}and{YOUR_DATA_APP_ID}, check the Endpoint URL in the endpoint Properties panel.
Note:
Make sure that all required dependencies are installed and correctly configured before previewing.
To preview your application in a local development server, run the following command:
yarn devYou can then open http://localhost:3000 in your browser and see the data from the test.repository database displayed on the page.