Last active
September 13, 2022 15:26
-
-
Save prohazko2/143910c9173674e57dd4d7eb7a72f66d to your computer and use it in GitHub Desktop.
otus-2021-10-lab27: fastapi example
This file contains 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
# > pip install uvicorn fastapi tinydb | |
# > python -m uvicorn main:app --port 8000 | |
from fastapi import FastAPI, Request, Query, HTTPException | |
from tinydb import TinyDB, Query | |
items = TinyDB('db.json').table('items') | |
app = FastAPI() | |
if len(items.all()) == 0: | |
items.insert({"id": 1, "name": "test 1"}) | |
items.insert({"id": 2, "name": "test 2"}) | |
@app.get("/") | |
async def index(): | |
return {"message": "Hello World"} | |
@app.api_route("/echo", methods=["GET", "POST", "PUT", "PATCH", "DELETE"]) | |
async def echo(request: Request): | |
body = {} | |
try: | |
body = await request.json() | |
except: | |
pass | |
return { | |
"method": request.method, | |
"url": str(request.url), | |
"query": request.query_params, | |
"headers": request.headers, | |
"body": body | |
} | |
@app.get("/items") | |
def get_items(): | |
return items.all() | |
@app.get("/items/{id}") | |
def get_item(id: int): | |
result = items.search(Query().id == id) | |
if len(result) == 0: | |
raise HTTPException(status_code=404, detail="Item not found") | |
return result[0] | |
@app.post("/items") | |
async def insert_item(request: Request): | |
item = await request.json() | |
if "id" not in item: | |
item["id"] = len(items.all()) + 1 | |
items.insert(item) | |
return item | |
@app.patch("/items/{id}") | |
async def update_item(request: Request, id: int): | |
body = await request.json() | |
items.update(body, Query().id == id) | |
return get_item(id) | |
@app.delete("/items/{id}") | |
def remove_item(id: int): | |
item = get_item(id) | |
items.remove(Query().id == id) | |
return item |
Author
prohazko2
commented
Feb 15, 2022
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment