Build an API to access D1 using a proxy Worker
In this tutorial, you will learn how to create an API that allows you to securely run queries against a D1 database.
This is useful if you want to access a D1 database outside of a Worker or Pages project, customize access controls and/or limit what tables can be queried.
D1's built-in REST API is best suited for administrative use as the global Cloudflare API rate limit applies.
To access a D1 database outside of a Worker project, you need to create an API using a Worker. Your application can then securely interact with this API to run D1 queries.
- Sign up for a Cloudflare account ↗.
- Install
Node.js
↗. - Have an existing D1 database. Refer to Get started tutorial for D1.
Node.js version manager
Use a Node version manager like Volta ↗ or
nvm ↗ to avoid permission issues and change
Node.js versions. Wrangler, discussed
later in this guide, requires a Node version of 16.17.0
or later.
Create a new Worker to create and deploy your API.
-
Create a Worker named
d1-http
by running:For setup, select the following options:
- For What would you like to start with?, choose
Hello World example
. - For Which template would you like to use?, choose
Hello World Worker
. - For Which language do you want to use?, choose
TypeScript
. - For Do you want to use git for version control?, choose
Yes
. - For Do you want to deploy your application?, choose
No
(we will be making some changes before deploying).
- For What would you like to start with?, choose
-
Change into your new project directory to start developing:
In this tutorial, you will use Hono ↗, an Express.js-style framework, to build the API.
-
To use Hono in this project, install it using
npm
:
You need an API key to make authenticated calls to the API. To ensure that the API key is secure, add it as a secret.
-
For local development, create a
.dev.vars
file in the root directory ofd1-http
. -
Add your API key in the file as follows.
Replace
YOUR_API_KEY
with a valid string value. You can also generate this value using the following command.
To initialize the application, you need to import the required packages, initialize a new Hono application, and configure the following middleware:
- Bearer Auth ↗: Adds authentication to the API.
- Logger ↗: Allows monitoring the flow of requests and responses.
- Pretty JSON ↗: Enables "JSON pretty print" for JSON response bodies.
-
Replace the contents of the
src/index.ts
file with the code below.
-
Add the following snippet into your
src/index.ts
.This adds the following endpoints:
- POST
/api/all
- POST
/api/exec
- POST
/api/batch
- POST
-
Start the development server by running the following command:
-
To test the API locally, open a second terminal.
-
In the second terminal, execute the below cURL command. Replace
YOUR_API_KEY
with the value you set in the.dev.vars
file.You should get the following output:
-
Stop the local server from running by pressing
x
in the first terminal.
The Hono application is now set up. You can test the other endpoints and add more endpoints if needed. The API does not yet return any information from your database. In the next steps, you will create a database, add its bindings, and update the endpoints to interact with the database.
If you do not have a D1 database already, you can create a new database with wrangler d1 create
.
-
In your terminal, run:
You may be asked to login to your Cloudflare account. Once logged in, the command will create a new D1 database. You should see a similar output in your terminal.
Make a note of the displayed database_name
and database_id
. You will use this to reference the database by creating a binding.
-
From your
d1-http
folder, open thewrangler.toml
file, Wrangler's configuration file. -
Add the following binding in the file. Make sure that the
database_name
and thedatabase_id
are correct. -
In your
src/index.ts
file, update theBindings
type by addingDB: D1Database
.
You can now access the database in the Hono application.
To create a table in your newly created database:
-
Create a new folder called
schemas
inside yourd1-http
folder. -
Create a new file called
schema.sql
, and paste the following SQL statement into the file.The code drops any table named
posts
if it exists, then creates a new tableposts
with the fieldid
,author
,title
,body
, andpost_slug
. It then uses an INSERT statement to populate the table. -
In your terminal, execute the following command to create this table:
Upon successful execution, a new table will be added to your database.
Your application can now access the D1 database. In this step, you will update the API endpoints to query the database and return the result.
-
In your
src/index.ts
file, update the code as follow.
In the above code, the endpoints are updated to receive query
and params
. These queries and parameters are passed to the respective functions to interact with the database.
- If the query is successful, you receive the result from the database.
- If there is an error, the error message is returned.
Now that the API can query the database, you can test it locally.
-
Start the development server by executing the following command:
-
In a new terminal window, execute the following cURL commands. Make sure to replace
YOUR_API_KEY
with the correct value.
If everything is implemented correctly, the above commands should result successful outputs.
Now that everything is working as expected, the last step is to deploy it to the Cloudflare network. You will use Wrangler to deploy the API.
-
To use the API in production instead of using it locally, you need to add the table to your remote (production) database. To add the table to your production database, run the following command:
You should now be able to view the table on the Cloudflare dashboard > Storage & Databases > D1. ↗
-
To deploy the application to the Cloudflare network, run the following command:
Upon successful deployment, you will get the link of the deployed app in the terminal (
DEPLOYED_APP_LINK
). Make a note of it. -
Generate a new API key to use in production.
-
Execute the
wrangler secret put
command to add an API to the deployed project.The terminal will prompt you to enter a secret value.
-
Enter the value of your API key (
YOUR_API_KEY
). Your API key will now be added to your project. Using this value you can make secure API calls to your deployed API. -
To test it, run the following cURL command with the correct
YOUR_API_KEY
andDEPLOYED_APP_LINK
.- Use the
YOUR_API_KEY
you have generated as the secret API key. - You can also find your
DEPLOYED_APP_LINK
from the Cloudflare dashboard > Workers & Pages >d1-http
> Settings > Domains & Routes.
- Use the
In this tutorial, you have:
- Created an API that interacts with your D1 database.
- Deployed this API to the Workers. You can use this API in your external application to execute queries against your D1 database. The full code for this tutorial can be found on GitHub ↗.
You can check out a similar implementation that uses Zod for validation in this GitHub repository ↗. If you want to build an OpenAPI compliant API for your D1 database, you should use the Cloudflare Workers OpenAPI 3.1 template ↗.