Skip to content

Build a Comments API

Last reviewed: 24 days ago

In this tutorial, you will use D1 and Hono to build a JSON API that stores and retrieves comments for a blog. You will create a D1 database, define a schema, and wire up GET and POST endpoints that read from and write to the database.

Prerequisites

  1. Sign up for a Cloudflare account.
  2. Install Node.js.

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.

1. Create a new Worker project

  1. Create a new project named d1-comments-api by running:

    npm create cloudflare@latest -- d1-comments-api

    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 Worker only.
    • 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).
  2. Move into the project directory:

    Terminal window
    cd d1-comments-api

2. Install Hono

Install Hono, a lightweight web framework for building APIs on Workers:

npm i hono

3. Create a database

  1. Create a new D1 database with Wrangler:

    Terminal window