-
Notifications
You must be signed in to change notification settings - Fork 69
Add FastAPI todobackend.com app example. #94
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| # FastAPI Todo Backend | ||
|
|
||
| A Python FastAPI implementation of the [Todo-Backend](https://todobackend.com) spec, running on Cloudflare Workers with D1 for storage. | ||
|
|
||
| ## Development | ||
|
|
||
| Initialize the local D1 database and start the dev server: | ||
|
|
||
| ```sh | ||
| uv run pywrangler d1 execute todos --local --file db_init.sql | ||
| uv run pywrangler dev | ||
| ``` | ||
|
|
||
| ## Testing with the Todo-Backend spec runner | ||
|
|
||
| Start the dev server, then open the spec runner pointing at your local instance: | ||
|
|
||
| ``` | ||
| https://todobackend.com/specs/index.html?http://localhost:8787/todos | ||
| ``` | ||
|
|
||
| You can also use the Todo-Backend client app: | ||
|
|
||
| ``` | ||
| https://todobackend.com/client/index.html?http://localhost:8787/todos | ||
| ``` | ||
|
|
||
| ## API | ||
|
|
||
| | Method | Path | Description | | ||
| | -------- | ---------------- | ------------------ | | ||
| | `GET` | `/todos` | List all todos | | ||
| | `POST` | `/todos` | Create a todo | | ||
| | `DELETE` | `/todos` | Delete all todos | | ||
| | `GET` | `/todos/{id}` | Get a single todo | | ||
| | `PATCH` | `/todos/{id}` | Update a todo | | ||
| | `DELETE` | `/todos/{id}` | Delete a todo | | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| CREATE TABLE IF NOT EXISTS todos ( | ||
| id TEXT PRIMARY KEY, | ||
| title TEXT NOT NULL DEFAULT '', | ||
| completed INTEGER NOT NULL DEFAULT 0, | ||
| "order" INTEGER | ||
| ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| { | ||
| "name": "fastapi-todo", | ||
| "version": "0.0.0", | ||
| "private": true, | ||
| "scripts": { | ||
| "deploy": "uv run pywrangler deploy", | ||
| "dev": "uv run pywrangler dev", | ||
| "start": "uv run pywrangler dev" | ||
| }, | ||
| "devDependencies": { | ||
| "wrangler": "^4.114.0" | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| [project] | ||
| name = "fastapi-todo" | ||
| version = "0.1.0" | ||
| description = "FastAPI todo backend conforming to the todobackend.com spec" | ||
| readme = "README.md" | ||
| requires-python = ">=3.12" | ||
| dependencies = [ | ||
| "fastapi", | ||
| ] | ||
|
|
||
| [dependency-groups] | ||
| dev = [ | ||
| "workers-py", | ||
| "workers-runtime-sdk" | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,134 @@ | ||
| import uuid | ||
|
|
||
| from fastapi.middleware.cors import CORSMiddleware | ||
|
|
||
| from fastapi import FastAPI, Request | ||
|
|
||
| app = FastAPI() | ||
|
|
||
| app.add_middleware( | ||
| CORSMiddleware, | ||
| allow_origins=["*"], | ||
| allow_methods=["*"], | ||
| allow_headers=["*"], | ||
| expose_headers=["*"], | ||
| ) | ||
|
|
||
|
|
||
| def _base_url(request: Request) -> str: | ||
| """Return the root URL for the todos collection.""" | ||
| return str(request.base_url).rstrip("/") + "/todos" | ||
|
|
||
|
|
||
| def _row_to_todo(row, request: Request) -> dict: | ||
| """Convert a D1 row into a todo dict with the absolute ``url`` field.""" | ||
| return { | ||
| "id": row.id, | ||
| "title": row.title, | ||
| "completed": bool(row.completed), | ||
| "order": row.order, | ||
| "url": f"{_base_url(request)}/{row.id}", | ||
| } | ||
|
|
||
|
|
||
| def _db(request: Request): | ||
| """Get the D1 database binding from the ASGI scope.""" | ||
| return request.scope["env"].DB | ||
|
|
||
|
|
||
| @app.get("/todos") | ||
| async def list_todos(request: Request): | ||
| results = await _db(request).prepare("SELECT * FROM todos").all() | ||
| return [_row_to_todo(r, request) for r in results.results] | ||
|
|
||
|
|
||
| @app.post("/todos") | ||
| async def create_todo(request: Request): | ||
| body = await request.json() | ||
| todo_id = str(uuid.uuid4()) | ||
| title = body.get("title", "") | ||
| completed = 1 if body.get("completed", False) else 0 | ||
| order = body.get("order") | ||
|
|
||
| await ( | ||
| _db(request) | ||
| .prepare( | ||
| 'INSERT INTO todos (id, title, completed, "order") VALUES (?, ?, ?, ?)' | ||
| ) | ||
| .bind(todo_id, title, completed, order) | ||
| .run() | ||
| ) | ||
|
|
||
| row = ( | ||
| await _db(request) | ||
| .prepare("SELECT * FROM todos WHERE id = ?") | ||
| .bind(todo_id) | ||
| .first() | ||
| ) | ||
|
|
||
| return _row_to_todo(row, request) | ||
|
|
||
|
|
||
| @app.delete("/todos") | ||
| async def delete_all_todos(request: Request): | ||
| await _db(request).prepare("DELETE FROM todos").run() | ||
| return [] | ||
|
|
||
|
|
||
| @app.get("/todos/{todo_id}") | ||
| async def get_todo(todo_id: str, request: Request): | ||
| row = ( | ||
| await _db(request) | ||
| .prepare("SELECT * FROM todos WHERE id = ?") | ||
| .bind(todo_id) | ||
| .first() | ||
| ) | ||
| if row is None: | ||
| return {"error": "not found"} | ||
| return _row_to_todo(row, request) | ||
|
|
||
|
|
||
| @app.patch("/todos/{todo_id}") | ||
| async def update_todo(todo_id: str, request: Request): | ||
| body = await request.json() | ||
| sets = [] | ||
| values = [] | ||
| if "title" in body: | ||
| sets.append("title = ?") | ||
| values.append(body["title"]) | ||
| if "completed" in body: | ||
| sets.append("completed = ?") | ||
| values.append(1 if body["completed"] else 0) | ||
| if "order" in body: | ||
| sets.append('"order" = ?') | ||
| values.append(body["order"]) | ||
|
|
||
| if sets: | ||
| values.append(todo_id) | ||
| await ( | ||
| _db(request) | ||
| .prepare(f"UPDATE todos SET {', '.join(sets)} WHERE id = ?") | ||
| .bind(*values) | ||
| .run() | ||
| ) | ||
|
|
||
| row = ( | ||
| await _db(request) | ||
| .prepare("SELECT * FROM todos WHERE id = ?") | ||
| .bind(todo_id) | ||
| .first() | ||
| ) | ||
| if row is None: | ||
| return {"error": "not found"} | ||
| return _row_to_todo(row, request) | ||
|
|
||
|
|
||
| @app.delete("/todos/{todo_id}") | ||
| async def delete_todo(todo_id: str, request: Request): | ||
| await _db(request).prepare("DELETE FROM todos WHERE id = ?").bind(todo_id).run() | ||
| return [] | ||
|
dom96 marked this conversation as resolved.
|
||
|
|
||
|
|
||
| import asgi | ||
|
|
||
| Default = asgi.entrypoint(app) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| { | ||
| "$schema": "node_modules/wrangler/config-schema.json", | ||
| "name": "fastapi-todo", | ||
| "main": "src/worker.py", | ||
| "compatibility_date": "2026-08-01", | ||
| "compatibility_flags": [ | ||
| "python_workers", | ||
| ], | ||
| "d1_databases": [ | ||
| { | ||
| "binding": "DB", | ||
| "database_name": "todos", | ||
| "database_id": "00000000-0000-0000-0000-000000000000" | ||
| } | ||
| ], | ||
| "observability": { | ||
| "enabled": true | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Interesting. Does this website have enough credibility / awareness that we can rely on? If so, do you think we should update all our examples to use the same backend to provide consistent examples?
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It seems to be someone's hobby project, but it has been around for a while, so yeah, I think we can rely on it.
I did suggest doing this in #89 (review). I think it would be nice to make these examples as simple as possible and make them easily comparable by them consistently implementing the todo-backend spec.