|
|
from typing import Union, Optional |
|
|
|
|
|
from fastapi import FastAPI |
|
|
from pydantic import BaseModel |
|
|
import uvicorn |
|
|
|
|
|
|
|
|
class User(BaseModel): |
|
|
name: str |
|
|
email: str |
|
|
password: str |
|
|
|
|
|
class Config: |
|
|
orm_mode = True |
|
|
|
|
|
|
|
|
app = FastAPI() |
|
|
|
|
|
|
|
|
@app.get("/") |
|
|
def read_root(): |
|
|
return {"Hello": "i like this"} |
|
|
|
|
|
|
|
|
@app.get("/items/works") |
|
|
def works(): |
|
|
return {"data": [{"id": 1, "name": "test1"}, {"id": 2, "name": "test2"}]} |
|
|
|
|
|
|
|
|
@app.get("/items/{item_id}") |
|
|
def read_item(item_id: int, q: Union[str, None] = None): |
|
|
return {"item_id": item_id, "q": q} |
|
|
|
|
|
|
|
|
database = {"1": {"name": "test1", "age": 18}, "2": {"name": "test2", "age": 19}} |
|
|
|
|
|
|
|
|
@app.get("/user") |
|
|
def read_user(id: str, key: Optional[str] = None): |
|
|
if key: |
|
|
return {"result": database[id][key]} |
|
|
return {"result": database[id]} |
|
|
|
|
|
|
|
|
@app.post("/user") |
|
|
def create_user(user: User): |
|
|
print(user) |
|
|
return {"data": f"succeed creating user {user.name}"} |
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
uvicorn.run(app, host="127.0.0.1", port=8000) |
|
|
|