mirror of
https://github.com/kennethreitz/responder.git
synced 2026-06-05 14:50:19 +00:00
ff6d530338
## About A few cosmetic adjustments aka. code formatting. Also validate the outcome on CI/GHA. Feel free to improve now or later at your disposal. ## Details The updates are based on using the most recent versions of pyproject-fmt and ruff. Specifically, spots marked with `noqa` might need further love, also at your disposal. --------- Co-authored-by: Kenneth Reitz <me@kennethreitz.org>
77 lines
1.6 KiB
Python
77 lines
1.6 KiB
Python
# Complete REST API example with Pydantic validation.
|
|
# https://responder.kennethreitz.org/tutorial-rest.html
|
|
from pydantic import BaseModel
|
|
|
|
import responder
|
|
|
|
|
|
class BookIn(BaseModel):
|
|
title: str
|
|
author: str
|
|
year: int
|
|
isbn: str | None = None
|
|
|
|
|
|
class BookOut(BaseModel):
|
|
id: int
|
|
title: str
|
|
author: str
|
|
year: int
|
|
isbn: str | None = None
|
|
|
|
|
|
api = responder.API(
|
|
title="Book Catalog",
|
|
version="1.0",
|
|
openapi="3.0.2",
|
|
docs_route="/docs",
|
|
)
|
|
|
|
books_db: dict[int, dict] = {}
|
|
next_id = 1
|
|
|
|
|
|
@api.route("/books", methods=["GET"])
|
|
def list_books(req, resp):
|
|
resp.media = list(books_db.values())
|
|
|
|
|
|
@api.route(
|
|
"/books",
|
|
methods=["POST"],
|
|
check_existing=False,
|
|
request_model=BookIn,
|
|
response_model=BookOut,
|
|
)
|
|
async def create_book(req, resp):
|
|
global next_id
|
|
data = await req.media()
|
|
book = {"id": next_id, **data}
|
|
books_db[next_id] = book
|
|
next_id += 1
|
|
resp.media = book
|
|
resp.status_code = 201
|
|
|
|
|
|
@api.route("/books/{book_id:int}", methods=["GET"])
|
|
def get_book(req, resp, *, book_id):
|
|
if book_id not in books_db:
|
|
resp.status_code = 404
|
|
resp.media = {"error": f"Book {book_id} not found"}
|
|
return
|
|
resp.media = books_db[book_id]
|
|
|
|
|
|
@api.route("/books/{book_id:int}", methods=["DELETE"], check_existing=False)
|
|
def delete_book(req, resp, *, book_id):
|
|
if book_id not in books_db:
|
|
resp.status_code = 404
|
|
resp.media = {"error": f"Book {book_id} not found"}
|
|
return
|
|
del books_db[book_id]
|
|
resp.status_code = 204
|
|
|
|
|
|
if __name__ == "__main__":
|
|
api.run()
|