A simple serverless REST API built with Cloudflare Workers and D1 database for managing a book collection.
Create Cloudflare Workers project:
npm create cloudflare@latest -- books-serverless-api
Note we are using the new json
wrangler configuration file.
Create D1 database:
npx wrangler d1 create prod-d1-books-serverless-api
Apply the D1 database schema with first examples:
npx wrangler d1 execute prod-d1-books-serverless-api --file=database_schema_01.sql --remote
GET /api/health
Returns the API's operational status and timestamp.
GET /api/stats
Returns overall statistics including total books, genre breakdown, and publication year range.
GET /api/books
Query Parameters:
page
(optional): Page number (default: 1)limit
(optional): Items per page (default: 10, max: 100)genre
(optional): Filter by genreyear
(optional): Filter by publication year
POST /api/books
Required fields:
{
"title": "string",
"author": "string",
"year": "number (optional)",
"isbn": "string (optional)",
"genre": "string (optional)",
"description": "string (optional)"
}
GET /api/books/:id
PUT /api/books/:id
Same fields as create book endpoint.
DELETE /api/books/:id
GET /api/books/search?q=query
Searches across title, author, genre, ISBN, year, and description fields.
curl "https://api.dlsdemo.com/api/books?page=1&limit=5"
curl "https://api.dlsdemo.com/api/books/search?q=fiction"
curl -X POST "https://api.dlsdemo.com/api/books" \
-H "Content-Type: application/json" \
-d '{
"title": "Neuromancer",
"author": "William Gibson",
"year": 1984,
"genre": "Science Fiction",
"isbn": "9780441569595",
"description": "A groundbreaking cyberpunk novel about a washed-up computer hacker hired for one last job."
}'
curl -X PUT "https://api.dlsdemo.com/api/books/1" \
-H "Content-Type: application/json" \
-d '{
"genre": "Classic Literature"
}'
CREATE TABLE books (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
author TEXT NOT NULL,
year INTEGER,
isbn TEXT,
genre TEXT,
description TEXT
);
Local development:
npm run dev
Deploy to Cloudflare:
npm run deploy
- Full CRUD operations for books
- Pagination and filtering
- Full-text search
- Input validation
- Error handling
- CORS support
- Health checking
- Statistics endpoint
This is a demonstration project showcasing Cloudflare Workers and D1 database capabilities. While it implements proper security measures and best practices, additional security considerations should be implemented for production use.
Educational purposes only.