Advertisement
fkudinov

Python Framework: FastApi

Nov 18th, 2024 (edited)
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.84 KB | Source Code | 0 0
  1. # file name:   main.py
  2. # install:     pip install "fastapi[standard]"
  3. # run command: fastapi dev main.py
  4. # host, port:  http://127.0.0.1:8000
  5.  
  6.  
  7. from fastapi import FastAPI
  8. from pydantic import BaseModel
  9.  
  10.  
  11. app = FastAPI()
  12.  
  13.  
  14. # in memory db
  15. BOOKS_DB = [{"book_id": 0, "book_name": "Hi there"},
  16.             {"book_id": 1, "book_name": "How are you?"}]
  17.  
  18.  
  19. @app.get("/book")
  20. async def show_books(count: int | None = None):
  21.     return {"books": BOOKS_DB[:count]}
  22.  
  23.  
  24. @app.get("/book/{book_id}")
  25. async def show_book(book_id: int):
  26.     return {book["book_id"]: book for book in BOOKS_DB}[book_id]
  27.  
  28.  
  29. class Book(BaseModel):
  30.     book_id: int | None = None
  31.     book_name: str
  32.  
  33.  
  34. @app.post("/book")
  35. async def create_book(book: Book):
  36.     data = book.dict()
  37.     data["book_id"] = int(len(BOOKS_DB))
  38.     BOOKS_DB.append(data)
  39.     return data
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement