備忘録

備忘録

PythonでFastAPIを利用してAPIサーバを構築する方法

Ⅰ. はじめに

タイトルの通り「PythonでFastAPIを利用してAPIサーバを構築する方法」です。

Ⅱ. サンプルプログラム

import secrets
import os
import uvicorn
from fastapi import FastAPI, HTTPException, Depends, status
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.openapi.utils import get_openapi
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from pydantic import BaseModel

app = FastAPI(title='My Perfect API', version='1.0.0', docs_url=None, redoc_url=None, openapi_url=None)
security = HTTPBasic()

class BaseResponse(BaseModel):
  success: bool

class SearchRequest(BaseModel):
  query: str | None

class SearchResponse(BaseResponse):
  text: str

def basicAuth(credentials: HTTPBasicCredentials = Depends(security)):
  correct_username = secrets.compare_digest(credentials.username, 'user001')
  correct_password = secrets.compare_digest(credentials.password, 'my_perfect_password')
  if not (correct_username and correct_password):
    raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED)

@app.get('/docs', include_in_schema=False)
async def get_documentation(_: HTTPBasicCredentials = Depends(security)):
  return get_swagger_ui_html(openapi_url='/openapi.json', title='docs')

@app.get('/openapi.json', include_in_schema=False)
async def openapi(_: HTTPBasicCredentials = Depends(security)):
  return get_openapi(title = app.title, version=app.version, routes=app.routes)

@app.get('/hello/{name}', summary='Say Hello')
def login(name: str, _: HTTPBasicCredentials = Depends(basicAuth)) -> JSONResponse:
  data = {
    'text': f'Hello {name}'
  }

  # strJson = jsonable_encoder(data)
  # return JSONResponse(content=strJson)
  return data

@app.post('/test001', summary='Search DB')
def tweetSearch(request: SearchRequest, _: HTTPBasicCredentials = Depends(basicAuth)) -> SearchResponse:
  # 検索処理
  result = DB.search(request.query)
  return SearchResponse(success=True, text=result)

if __name__ == '__main__':
  uvicorn.run('web:app', host='127.0.0.1', port=8000, log_level='info', reload=True)

実行結果

省略