Programming Language/Python
[FastAPI] 1. 간단한 FastAPI 만들기
LeeJaeJun
2024. 6. 18. 14:29
728x90
728x90
FastAPI 애플리케이션 기본 구조
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
- Import FastAPI
- from fastapi import FastAPI
- FastAPI는 API에 대한 모든 기능을 제공하는 Python 클래스
- Create a FastAPI "Instance"
- app = FastAPI()
- FastAPI application insatnce 생성
- Instance를 가지고 앞으로 사용할 API경로를 정의하고 각 경로에 대한 요청을 처리하는 엔드포인트(함수)를 등록하는데 사용
- API를 만드는데 있어서의 중심점 역할을 하는 instance
- Define a path operation decorator
- @app.get("/")
- path란 URL에서 처음 나오는 / 부터를 의미
- URL이 https://example.com/items/foo라면 path는 /items/foo
- FastAPI에서 operation은 HTTP method들 중에 하나를 의미 (여러 개를 함께 사용하기도 함)
- POST: 데이터 생성
- GET: 데이터 읽기
- PUT: 데이터 업데이트
- DELETE: 데이터 삭제
- OPTIONS, HEAD, PATCH, TRACE 등등
- @app.get("/")은 app이라는 instance를 통해 루트 경로("/")에 대한 HTTP GET 요청을 처리할 함수를 지정하겠다는 의미
- Define the path operation function
- async def root():
- 위에서 정의한 path operation에 대한 요청이 들어왔을 때 실행할 함수
- async는 비동기 함수라는 것을 정의하는 것이기에 비동기 처리를 하는 것이 아니면 안붙여도 됨
- 위 예시에서는 루트 경로("/")에 대해서 GET 요청이 들어오면 root()라는 함수를 실행한다는 의미가 됨
- Return the content
- return {"message": "Hello World"}
- 리턴값이 꼭 있을 필요는 없음
- dictionary, list, str, int, Pydantic 모델 등 다양한 값 반환 가능
따라서 위 API의 경우 루트 경로에 대해서 GET 요청이 들어오면 {"message": "Hello World"}라는 JSON 응답을 반환하는 것이다.
https://fastapi.tiangolo.com/tutorial/first-steps/
First Steps - FastAPI
FastAPI framework, high performance, easy to learn, fast to code, ready for production
fastapi.tiangolo.com
728x90
300x250