Skip to content

DavidJKTofan/cf-petstore-api-workers

Repository files navigation

Mini-Copy of Swagger Petstore API on Cloudflare Workers + D1

This project attempts to implement the Swagger Petstore API using Cloudflare Workers and Cloudflare D1 database. It provides a fully functioning REST API for a pet store, including endpoints for managing pets, orders, and users.

Features

  • RESTful API following OpenAPI/Swagger Petstore specification
  • Persistent storage using Cloudflare D1 (SQLite-based serverless database)
  • Serverless architecture with Cloudflare Workers
  • Authentication implemented with Cloudflare API Shield JWT Validation
  • Complete CRUD operations for pets, users, and orders

You can upload the openapi.yaml file to Cloudflare API Shield Schema Validation.

Upload the public-private-keypair.json from mkjwk.org generator to Cloudflare API Shield token configuration.

Deployment

Prerequisites

Quickstart

Deploy to Cloudflare

Setup

  1. Install Wrangler CLI:
npm install wrangler --save-dev
  1. Authenticate with your Cloudflare account:
npx wrangler login
  1. Clone this repository:
git clone https://github.com/DavidJKTofan/petstore-api-workers.git
cd petstore-api-workers
  1. Create a D1 database:
npx wrangler d1 create petstore

Make sure you don't already have a D1 database called petstore.

  1. Update your wrangler.jsonc configuration file with the database ID from the previous step:
{
	"$schema": "node_modules/wrangler/config-schema.json",
	"name": "petstore-api",
	"main": "src/index.js",
	"compatibility_date": "2025-03-20",
	"observability": {
		"enabled": true
	},
	"d1_databases": [
		{
			"binding": "PETSTORE_DB",
			"database_name": "petstore",
			"database_id": "6c662a4b-91d5-482e-8032-fd19c28cae9d"
		}
	]
}
  1. Create the database schema:
npx wrangler d1 execute petstore --file=schema.sql --remote
  1. Add sample data (optional):
npx wrangler d1 execute petstore --file=sample-data.sql --remote
  1. Deploy your Worker:
npx wrangler deploy

API Documentation

This API implements the Swagger Petstore specification. Below are examples of how to use the key endpoints.

Base URL

https://petstore.automatic-demo.com/api/v3

Authentication

Many endpoints require an API key for authentication:

api-key-petstore: your_api_key

Pass this key in the header of your requests.

Pet Endpoints

Create a new pet

curl -X POST "https://petstore.automatic-demo.com/api/v3/pet" \
  -H "Content-Type: application/json" \
  -H "api-key-petstore: your_api-key-petstore" \
  -d '{
    "name": "Doggo",
    "photoUrls": ["https://example.com/doggo.jpg"],
    "status": "available",
    "category": {
      "id": 1,
      "name": "Dogs"
    },
    "tags": [
      {
        "id": 1,
        "name": "friendly"
      }
    ]
  }'

Get a pet by ID

curl -X GET "https://petstore.automatic-demo.com/api/v3/pet/1" \
  -H "api-key-petstore: your_api-key-petstore"

Update an existing pet

curl -X PUT "https://petstore.automatic-demo.com/api/v3/pet" \
  -H "Content-Type: application/json" \
  -H "api-key-petstore: your_api-key-petstore" \
  -d '{
    "id": 1,
    "name": "Doggo Updated",
    "photoUrls": ["https://example.com/doggo.jpg"],
    "status": "pending",
    "category": {
      "id": 1,
      "name": "Dogs"
    },
    "tags": [
      {
        "id": 1,
        "name": "friendly"
      }
    ]
  }'

Find pets by status

curl -X GET "https://petstore.automatic-demo.com/api/v3/pet/findByStatus?status=available" \
  -H "api-key-petstore: your_api-key-petstore"

Find pets by tags

curl -X GET "https://petstore.automatic-demo.com/api/v3/pet/findByTags?tags=friendly&tags=trained" \
  -H "api-key-petstore: your_api-key-petstore"

Delete a pet

curl -X DELETE "https://petstore.automatic-demo.com/api/v3/pet/1" \
  -H "api-key-petstore: your_api-key-petstore"

Upload an image for a pet

curl -X POST "https://petstore.automatic-demo.com/api/v3/pet/1/uploadImage" \
  -H "api-key-petstore: your_api-key-petstore" \
  -F "[email protected]" \
  -F "additionalMetadata=Profile photo for pet"

Store Endpoints

Get inventory by status

curl -X GET "https://petstore.automatic-demo.com/api/v3/store/inventory" \
  -H "api-key-petstore: your_api-key-petstore"

Place an order

curl -X POST "https://petstore.automatic-demo.com/api/v3/store/order" \
  -H "Content-Type: application/json" \
  -d '{
    "petId": 2,
    "quantity": 1,
    "shipDate": "2023-08-01T10:00:00Z",
    "status": "placed",
    "complete": false
  }'

Get order by ID

curl -X GET "https://petstore.automatic-demo.com/api/v3/store/order/1"

Delete an order

curl -X DELETE "https://petstore.automatic-demo.com/api/v3/store/order/1"

User Endpoints

Create a user

curl -X POST "https://petstore.automatic-demo.com/api/v3/user" \
  -H "Content-Type: application/json" \
  -d '{
    "username": "user1",
    "firstName": "Test",
    "lastName": "User",
    "email": "[email protected]",
    "password": "password123",
    "phone": "555-123-4567",
    "userStatus": 1
  }'

Create multiple users with list

curl -X POST "https://petstore.automatic-demo.com/api/v3/user/createWithList" \
  -H "Content-Type: application/json" \
  -d '[
    {
      "username": "user2",
      "firstName": "Test",
      "lastName": "User2",
      "email": "[email protected]",
      "password": "password456",
      "phone": "555-234-5678",
      "userStatus": 1
    },
    {
      "username": "user3",
      "firstName": "Test",
      "lastName": "User3",
      "email": "[email protected]",
      "password": "password789",
      "phone": "555-345-6789",
      "userStatus": 1
    }
  ]'

User login

curl -X GET "https://petstore.automatic-demo.com/api/v3/user/login?username=user1&password=password123"

User logout

curl -X GET "https://petstore.automatic-demo.com/api/v3/user/logout"

Get user by username

curl -X GET "https://petstore.automatic-demo.com/api/v3/user/user1"

Update a user

curl -X PUT "https://petstore.automatic-demo.com/api/v3/user/user1" \
  -H "Content-Type: application/json" \
  -d '{
    "firstName": "Updated",
    "lastName": "User",
    "email": "[email protected]"
  }'

Delete a user

curl -X DELETE "https://petstore.automatic-demo.com/api/v3/user/user1"

Database Schema

The API uses the following tables:

  • pets: Stores basic pet information
  • categories: Pet categories
  • pet_photos: URLs of pet photos (many-to-one relationship with pets)
  • pet_tags: Pet tags (many-to-many relationship)
  • inventory: Counts of pets by status
  • orders: Store orders
  • users: User accounts

Development

Local Development

Start a local development server:

npx wrangler dev

Simulating traffic

Simulate API traffic for testing purposes and to populate analytics.

Use a virtual environment:

python -m venv PETSTORE_API
source PETSTORE_API/bin/activate

Install dependencies:

pip install "httpx[http2]" # Uses HTTP version HTTP/2 
pip install authlib cryptography # for JWT Tokens

Required Arguments

  • --url: The base URL of the Petstore API you want to test
  • --api-key: Your API key for authentication

Optional Arguments

  • --duration: How long to run the simulation in minutes (default: 10)
  • --rate: Operations per minute to perform (default: 30)
  • --min-pets: Minimum number of pets to maintain (default: 10)
  • --min-users: Minimum number of users to maintain (default: 5)
  • --min-orders: Minimum number of orders to maintain (default: 3)
  • --parallel: Number of parallel threads for concurrent operations (default: 0, which means sequential operation)

Simulate run with JWT Tokens only (preferred):

python traffic-simulator.py --url "https://petstore.automatic-demo.com/api/v3/" --duration 30 --rate 60 --min-pets 10 --min-users 10 --parallel 3 --use-jwt

Simulate run with API Key only:

python traffic-simulator.py --url "https://petstore.automatic-demo.com/api/v3/" --api-key "special-key" --duration 30 --rate 60 --min-pets 10 --min-users 10 --parallel 3
  • Run the simulator for 30 minutes
  • Generate about 60 operations per minute per thread
  • Maintain at least 20 pets and 10 users in the system
  • Run 3 concurrent threads (for a total of ~180 operations per minute)

Modifying the Schema

If you need to modify the database schema:

  1. Update the schema.sql file
  2. Apply changes to your D1 database:
npx wrangler d1 execute petstore --file=schema.sql

Note: This will attempt to recreate tables that already exist, which is safe due to the IF NOT EXISTS clauses.


Disclaimer

Educational purposes only.

All trademarks, logos and brand names are the property of their respective owners. All company, product and service names used in this website are for identification and/or educational purposes only. Use of these names, trademarks and brands does not imply endorsement.

This repo does not reflect the opinions of, and is not affiliated with any of the institutions mentioned here.

About

Famous Petstore API deployed on Cloudflare Developer Platform as a Serverless API.

Topics

Resources

License

Stars

Watchers

Forks