Skip to content

Instantly share code, notes, and snippets.

@DeoLeung
Created March 12, 2024 03:14
Show Gist options
  • Save DeoLeung/bc8be105cdd0b07aee0b621c3ae9ce17 to your computer and use it in GitHub Desktop.
Save DeoLeung/bc8be105cdd0b07aee0b621c3ae9ce17 to your computer and use it in GitHub Desktop.
generate openapi.json with fastapi
"""python scripts/sample_openapi_spec.py openapi.json title version"""
import json
import sys
import fastapi
from fastapi import Body
from fastapi import Depends
from fastapi import Query
from fastapi.openapi.utils import get_openapi
from fastapi.security import APIKeyHeader
from pydantic import BaseModel
app = fastapi.FastAPI()
# user write api definition here
# define security
security = APIKeyHeader(name='api_key', scheme_name='api_key')
security2 = APIKeyHeader(name='token', scheme_name='token')
# define api
@app.get('/health')
def health(a: int = Query(..., description='a'),
token: str = Depends(security2)):
"""check health"""
pass
class Health(BaseModel):
power: str = 'on'
@app.post('/health')
def health(a: int = Query(..., description='a'),
data: Health = Body(..., description='health data'),
token: str = Depends(security)):
"""modify health"""
pass
# define server
server = [{"url": "http://localhost:8000"}]
# end
def check_duplicated_operation_id(schema):
operation_ids = [
api['operationId'] for path in schema['paths'].values()
for api in path.values()
]
duplicated = set(a for a in operation_ids if operation_ids.count(a) > 1)
if len(duplicated) > 0:
raise ValueError(f'found duplicated operation ids: {duplicated}')
openapi_schema = get_openapi(
title=sys.argv[2],
version=sys.argv[3],
routes=app.routes,
servers=server,
)
check_duplicated_operation_id(openapi_schema)
with open(sys.argv[1], 'w') as f:
json.dump(openapi_schema, f, indent=2, ensure_ascii=False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment