[REQ] [Python-Fastapi] Add status_code in route decorators based on OpenAPI 2xx
Is your feature request related to a problem? Please describe.
When using the python-fastapi generator, the generated endpoints do not set the status_code argument on the FastAPI route decorators, even when the OpenAPI specification clearly defines a specific success status code.
For example, given an OpenAPI operation like:
paths:
/example:
post:
summary: Create example
operationId: createExample
responses:
'201':
description: Created
content:
application/json:
schema:
$ref: '#/components/schemas/ExampleResponse'
'400':
description: Bad Request
'500':
description: Server Error
the generated FastAPI router looks roughly like this:
@router.post(
"/example",
responses={
201: {"model": ExampleResponse, "description": "Created"},
400: {"model": Message, "description": "Bad Request"},
500: {"model": Message, "description": "Server Error"},
},
summary="Create example",
response_model_by_alias=True,
)
async def create_example(
body: ExampleRequest = Body(None),
) -> ExampleResponse:
return await BaseExampleApi.subclasses[0]().create_example(body)
FastAPI’s default HTTP status code for this route is 200, because the decorator does not specify status_code. This is inconsistent with the OpenAPI spec, which documents 201 as the success status. According to the FastAPI documentation (https://fastapi.tiangolo.com/reference/status/), the status_code argument should be used to make the runtime behavior match the documented success status.
Describe the solution you'd like
I would like the python-fastapi generator to set the status_code argument on the generated route decorator when the OpenAPI spec clearly defines a primary success code.
For example, for the previous spec the generator could emit:
@router.post(
"/example",
responses={
201: {"model": ExampleResponse, "description": "Created"},
400: {"model": Message, "description": "Bad Request"},
500: {"model": Message, "description": "Server Error"},
},
summary="Create example",
response_model_by_alias=True,
status_code=status.HTTP_201_CREATED,
)
async def create_example(
body: ExampleRequest = Body(None),
) -> ExampleResponse:
...
This way:
The runtime HTTP status code matches the OpenAPI documentation. The generated code follows FastAPI’s recommended pattern of using constants from fastapi.status as described in https://fastapi.tiangolo.com/reference/status/. One simple heuristic could be:
If there is exactly one 2xx response defined, use that as the status_code. Optionally, allow an explicit override via a vendor extension such as x-default-status-code on the operation.
Describe alternatives you've considered
- Manual edits after generation: After each code generation, manually edit the generated FastAPI router modules to add status_code=status.HTTP_201_CREATED (or similar) to each decorator. This is error-prone and must be repeated every time the code is regenerated.