728x90
1. 설치 https://fastapi.tiangolo.com/#installation
pip install fastapi
pip install uvicorn # for ASGI(Asynchronous Server Gateway Interface) server
2. Run the server with the command below.
uvicorn {file_name}:app --reload
# ex) uvicorn main:app --reload
# INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
# INFO: Started reloader process [28720]
# INFO: Started server process [28722]
# INFO: Waiting for application startup.
# INFO: Application startup complete.
3-1. 예제 코드 (GET, GET with parameter)
from fastapi import FastAPI
app = FastAPI()
# method: get, endpoint: "/"
@app.get('/my-first-api')
def hello():
return {"message": "Hello-world"}
# URL: http://127.0.0.1:8000/my-first-api
# RETURN: {"message": "Hello-world"}
#################################
# FastAPI check type of data that we pass it in the call
@app.get('/my-first-api')
def hello(name: str):
return {"message": f"Hello {name}..."}
# URL: http://127.0.0.1:8000/my-first-api?name=thxxyj
# RETURN: {"message": "Hello thxxyj..."}
https://anderfernandez.com/en/blog/how-to-create-api-python/
3-2. 예제코드 (GET, PUT)
from fastapi import FastAPI
from typing import Union
from pydantic import BaseModel
app = FastAPI()
# method: GET
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str):
return {"item_id": item_id, "q": q}
#################################
# method: PUT
class Item(BaseModel):
name: str
price: float
is_offer: Union[bool, None] = None
@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
return {"item_name": item.name, "item_id": item_id}
4. FastAPI는 자동으로 documents를 제공한다.
http://127.0.0.1:8000/docs -> Swagger - Interactive API docs
http://127.0.0.1:8000/redoc -> Redoc - Alternative API docs
728x90
'Python > FastAPI' 카테고리의 다른 글
FastAPI Docker로 배포하기 (0) | 2024.03.15 |
---|---|
FastAPI parameters: path, query, request body (0) | 2024.03.05 |