Skip to content

Instantly share code, notes, and snippets.

@prohazko2
Last active September 13, 2022 15:26
Show Gist options
  • Save prohazko2/143910c9173674e57dd4d7eb7a72f66d to your computer and use it in GitHub Desktop.
Save prohazko2/143910c9173674e57dd4d7eb7a72f66d to your computer and use it in GitHub Desktop.
otus-2021-10-lab27: fastapi example
# > 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
@prohazko2
Copy link
Author

prohazko2 commented Feb 15, 2022

GET http://127.0.0.1:8000/

### echo test
POST http://127.0.0.1:8000/echo?&q1=foo&q2=bar
Content-Type: application/json
X-Test-Foo: Bar

{"foo": "bar", "x": 10}


### get items
GET http://127.0.0.1:8000/items

### create item
POST http://127.0.0.1:8000/items
Content-Type: application/json

{"id": 3, "name": "test 3"}

### update item
PATCH http://127.0.0.1:8000/items/3
Content-Type: application/json

{"name": "test *"}

### delete item
DELETE http://127.0.0.1:8000/items/3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment