This is a Cloudflare Worker with OpenAPI 3.1 Auto Generation and Validation using chanfana and Hono.
This is an example project made to be used as a quick start into building OpenAPI compliant Workers that generates the
openapi.json
schema automatically from code and validates the incoming request to the defined parameters or request body.
This template includes various endpoints, a D1 database, and integration tests using Vitest as examples. In endpoints, you will find chanfana D1 AutoEndpoints and a normal endpoint to serve as examples for your projects.
Besides being able to see the OpenAPI schema (openapi.json) in the browser, you can also extract the schema locally no hassle by running this command npm run schema
.
Important
When using C3 to create this project, select "no" when it asks if you want to deploy. You need to follow this project's setup steps before deploying.
Outside of this repo, you can start a new project with this template using C3 (the create-cloudflare
CLI):
npm create cloudflare@latest -- --template=cloudflare/templates/openapi-template
A live public deployment of this template is available at https://openapi-template.templates.workers.dev
- Install the project dependencies with a package manager of your choice:
npm install
- Create a D1 database with the name "openapi-template-db":
...and update the
npx wrangler d1 create openapi-template-db
database_id
field inwrangler.json
with the new database ID. - Run the following db migration to initialize the database (notice the
migrations
directory in this project):npx wrangler d1 migrations apply DB --remote
- Deploy the project!
npx wrangler deploy
- Monitor your worker
npx wrangler tail
This template includes integration tests using Vitest. To run the tests locally:
npm run test
Test files are located in the tests/
directory, with examples demonstrating how to test your endpoints and database interactions.
- Your main router is defined in
src/index.ts
. - Each endpoint has its own file in
src/endpoints/
. - Integration tests are located in the
tests/
directory. - For more information read the chanfana documentation, Hono documentation, and Vitest documentation.