https://slender-danger-059.notion.site/2-First-Steps-87923b1bf0634a499793c1bb300dd482
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
다음과 같이 main.py를 구성
uvicorn main:app --reload
그 후, 다음과 같은 커맨드로 서버를 시작. 그러면 아래와 같은 메세지가 뜬다. 이 메세지는 local machine에서 app이 제공하는 URL을 나타낸다.
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
FastAPI는 API를 정의하기 위한 OpenAPI ****표준을 사용하여 모든 API에 "스키마"를 생성한다.
**Schema**
API schema
Data schema
**OpenAPI and JSON Schema**
용도
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
FastAPI는 API에 대한 모든 기능을 제공하는 파이썬 class. 또한, FastAPI는 Starlette를 직접 상속하는 class. 따라서, FastAPI로 Starlette의 모든 기능을 사용할 수 있음.
Starlette이란?
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
app은 FastAPI 클래스의 인스턴스. 이것은 모든 API를 생성하기 위한 필수적인 지점. 물론, 이름이 꼭 app일 필요하는 없음. 단, app이 아니라고 하면 서버 실행 시 커맨드 또한 바뀌어야 함.
path(경로)
여기서 경로는 앤드포인트 or 라우트 라고도 불린다. URL의 마지막 부분. path는 관심사와 리소스를 분리하는 주요 방법.
operation(동작)
HTTP method 중 하나를 나타낸다. 다음 중 하나.
이국적인 것들도 있음.
**Define a path operation decorator**
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
@app.get("/")은 다음의 요청을 하는 것을 알 수 있음
@decorator
파이썬의 문법으로 함수를 수정하지 않은 상태에서 추가 기능을 구현할 때 사용. 아래 있는 함수를 받고 그걸 이용해 무언가 로직을 처리. @app.get("/") 데코레이터같은 경우 아래 함수가 경로 / 에 해당하는 get 동작을 하라고 알려준다.
다음과 같은 함수를 **path operation function(경로 동작 함수)**라고 한다.
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
다음과 같은 함수는 비동기(async)함수이다. 당연히 앞에 async를 붙이지 않으면 일반 함수로 사용가능하다.
“async def syntac“ path operation function ?
results = await some_library()
@app.get('/')
async def read_results():
results = await some_library()
return results
@app.get('/')
def results():
results = some_library()
return results
Concurrency and async / await - FastAPI
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
객체, 배열, 문자열, 숫자 등을 반환할 수 있다. Pydantic model도 반환할 수 있으며 ORM을 포함하여 JSON으로 자동 변환되는 객체들과 모델들도 많다.
Pydantic?