-
[Python] FastAPI 사용법Engineering WIKI/Python 2021. 4. 13. 23:05
- 아래 명령어를 이용하여 fastapi를 설치한다.
$ pip install fastapi
$ pip install uvicorn[standard]
- crate a main.py
from typing import Optional from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"Hello": "World"} @app.get("/items/{item_id}") def read_item(item_id: int, q: Optional[str] = None): return {"item_id": item_id, "q": q}
Run it
Run the server with:
$ 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.Check it¶
Open your browser at http://127.0.0.1:8000/items/5?q=somequery.
You will see the JSON response as:
{"item_id": 5, "q": "somequery"}
You already created an API that:
- Receives HTTP requests in the paths / and /items/{item_id}.
- Both paths take GET operations (also known as HTTP methods).
- The path /items/{item_id} has a path parameter item_id that should be an int.
- The path /items/{item_id} has an optional str query parameter q.
from typing import Optional from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float is_offer: Optional[bool] = None @app.get("/") def read_root(): return {"Hello": "World"} @app.get("/items/{item_id}") def read_item(item_id: int, q: Optional[str] = None): return {"item_id": item_id, "q": q} @app.put("/items/{item_id}") def update_item(item_id: int, item: Item): return {"item_name": item.name, "item_id": item_id}
'Engineering WIKI > Python' 카테고리의 다른 글
[Python] 파이썬 인스턴스 메서드 / 정적 메서드 / 클래스 메서드 (0) 2022.04.12 알고리즘 INPUT값 TXT 파일로 입력하기 (Feat. VSC) (0) 2022.04.07 Class Advanced (0) 2022.04.06 [Python] itertools 완전탐색 (0) 2022.03.06 [Python] One-line Tree in Python (0) 2021.02.21 [Python] pyinstaller 실행파일 생성 (0) 2021.02.21 Pandas 텍스트(txt) 파일 불러오기 및 저장하기 (0) 2021.02.03 [Python] 소요시간 측정방법 (0) 2020.12.09