-
Notifications
You must be signed in to change notification settings - Fork 1
/
fastapi-example.py
79 lines (61 loc) · 1.73 KB
/
fastapi-example.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# This example demonstrates how to use Dante with FastAPI.
#
# To run this example, you need to install FastAPI:
#
# $ pip install fastapi[standard]
#
# Then, you can run the FastAPI server:
#
# $ cd examples/
# $ fastapi dev fastapi-example.py
#
# And visit http://localhost:8000/docs to interact with the API.
from __future__ import annotations
from datetime import date
from typing import Optional
from fastapi import FastAPI, HTTPException, status
from pydantic import BaseModel
from dante import Dante
class Book(BaseModel):
isbn: str
title: str
authors: list[str]
published_date: date
summary: Optional[str] = None
app = FastAPI()
db = Dante("books.db", check_same_thread=False)
books = db[Book]
@app.get("/books/")
def list_books() -> list[Book]:
return books.find_many()
@app.post("/books/", status_code=status.HTTP_201_CREATED)
def create_book(book: Book):
books.insert(book)
return book
@app.get("/books/{isbn}")
def get_book(isbn: str):
book = books.find_one(isbn=isbn)
if book is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Book not found",
)
return book
@app.put("/books/{isbn}")
def update_book(isbn: str, book: Book):
n = books.update(book, isbn=isbn)
if not n:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Book not found",
)
return book
@app.delete("/books/{isbn}", status_code=status.HTTP_204_NO_CONTENT)
def delete_book(isbn: str):
n = books.delete(isbn=isbn)
if not n:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Book not found",
)
return {"message": "Book deleted"}