Last active
November 4, 2021 17:28
-
-
Save goodbyegangster/13bff0732a03576636b3ed9cf84c3bbe to your computer and use it in GitHub Desktop.
FastAPI Tutorial
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
""" | |
FastAPIの基本的記法 | |
- Python 3.9.7 | |
- FastAPI 0.70.0 | |
- uvicorn 0.15.0 | |
""" | |
import uvicorn | |
from typing import Optional | |
from fastapi import FastAPI, Query, HTTPException | |
from pydantic import Field, BaseModel | |
app = FastAPI() | |
# basic | |
@app.get("/") | |
async def root(): | |
return {"message": "Hello"} | |
# path parameter | |
@app.get("/users/{name}") | |
async def get_user(name: str): | |
return {"name": name} | |
# query parameter | |
@app.get("/users/id/{name}") | |
async def get_name_with_id(name: str, id: Optional[int] = None): | |
return {"name": name, "id": id} | |
# query parameter and validation | |
@app.get("/v2/users/id/{name}") | |
async def get_name_with_id_validation(name: str, id: str = Query(..., regex="^[0-9]{2}$")): | |
return {"name": name, "id": id} | |
class User(BaseModel): | |
name: str | |
age: Optional[int] = None | |
# post | |
@app.post("/users/") | |
async def post_user(user: User): | |
return user | |
class UserWithMeta(BaseModel): | |
name: str = Field(..., title="Name", description="Name of User") | |
age: Optional[int] = Field(None, title="age", description="Age of User") | |
# post with meta data | |
@app.post("/v2/users/") | |
async def post_user_with_meta(user: UserWithMeta): | |
return user | |
# response with response_model | |
@app.post("/v3/users/", response_model=User) | |
async def post_by_response_model(user: User): | |
return user | |
# specify http status code | |
@app.get("/users/201/", status_code=201) | |
async def get_201(): | |
return {"Hello": "World"} | |
# raise 400 error | |
@app.get("/users/404/") | |
async def get_404(): | |
raise HTTPException(status_code=404, detail="User not found") | |
if __name__ == "__main__": | |
uvicorn.run("main:app", host="0.0.0.0", port=8080, timeout_keep_alive=0, log_level="debug", reload=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment