Build a Comments API
In this tutorial, you will learn how to use D1 to add comments to a static blog site. To do this, you will construct a new D1 database, and build a JSON API that allows the creation and retrieval of comments.
Use C3 ↗, the command-line tool for Cloudflare's developer products, to create a new directory and initialize a new Worker project:
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
JavaScript
. - 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).
To start developing your Worker, cd
into your new project directory:
In this tutorial, you will use Hono ↗, an Express.js-style framework, to build your API. To use Hono in this project, install it using npm
:
In src/worker.js
, initialize a new Hono application, and define the following endpoints:
GET /api/posts/:slug/comments
.POST /api/posts/:slug/comments
.
You will now create a D1 database. In Wrangler v2, there is support for the wrangler d1
subcommand, which allows you to create and query your D1 databases directly from the command line. Create a new database with wrangler d1 create
:
Reference your created database in your Worker code by creating a binding inside of your wrangler.toml
file, Wrangler's configuration file. Bindings allow us to access Cloudflare resources, like D1 databases, KV namespaces, and R2 buckets, using a variable name in code. In wrangler.toml
, set up the binding DB
and connect it to the database_name
and database_id
:
With your binding configured in your wrangler.toml
file, you can interact with your database from the command line, and inside your Workers function.
Interact with D1 by issuing direct SQL commands using wrangler d1 execute
:
You can also pass a SQL file - perfect for initial data seeding in a single command. Create schemas/schema.sql
, which will create a new comments
table for your project:
With the file created, execute the schema file against the D1 database by passing it with the flag --file
:
In earlier steps, you created a SQL database and populated it with initial data. Now, you will add a route to your Workers function to retrieve data from that database. Based on your wrangler.toml
configuration in previous steps, your D1 database is now accessible via the DB
binding. In your code, use the binding to prepare SQL statements and execute them, for example, to retrieve comments:
The above code makes use of the prepare
, bind
, and all
functions on a D1 binding to prepare and execute a SQL statement. Refer to D1 Workers Binding API for a list of all methods available.
In this function, you accept a slug
URL query parameter and set up a new SQL statement where you select all comments with a matching post_slug
value to your query parameter. You can then return it as a JSON response.
The previous steps grant read-only access to your data. To create new comments by inserting data into the database, define another endpoint in src/worker.js
:
With your application ready for deployment, use Wrangler to build and deploy your project to the Cloudflare network.
Begin by running wrangler whoami
to confirm that you are logged in to your Cloudflare account. If you are not logged in, Wrangler will prompt you to login, creating an API key that you can use to make authenticated requests automatically from your local machine.
After you have logged in, confirm that your wrangler.toml
file is configured similarly to what is seen below. You can change the name
field to a project name of your choice:
Now, run npx wrangler deploy
to deploy your project to Cloudflare.
When it has successfully deployed, test the API by making a GET
request to retrieve comments for an associated post. Since you have no posts yet, this response will be empty, but it will still make a request to the D1 database regardless, which you can use to confirm that the application has deployed correctly:
This application is an API back-end, best served for use with a front-end UI for creating and viewing comments. To test this back-end with a prebuild front-end UI, refer to the example UI in the example-frontend directory ↗. Notably, the loadComments
and submitComment
functions ↗ make requests to a deployed version of this site, meaning you can take the frontend and replace the URL with your deployed version of the codebase in this tutorial to use your own data.
Interacting with this API from a front-end will require enabling specific Cross-Origin Resource Sharing (or CORS) headers in your back-end API. Hono allows you to enable Cross-Origin Resource Sharing for your application. Import the cors
module and add it as middleware to your API in src/worker.js
:
Now, when you make requests to /api/*
, Hono will automatically generate and add CORS headers to responses from your API, allowing front-end UIs to interact with it without erroring.
In this example, you built a comments API for powering a blog. To see the full source for this D1-powered comments API, you can visit cloudflare/workers-sdk/templates/worker-d1-api ↗.