Appearance
OpenAPI Export with FastAPI
FastAPI natively supports OpenAPI export, but it defaults to OpenAPI version 3.1, which is not fully supported by Azure API Management (APIM). To ensure compatibility, the OpenAPI schema must be downgraded to version 3.0.1. This conversion is handled automatically by a script in the pipeline.
For FastAPI, no extra configuration is required in your application. The pipeline is already set up to use FastAPI's TestClient to export the OpenAPI specification.
1. Modifying Your Pipeline
Currently, the schema generator only supports generate_schema_fastapi.py. If you use a different framework, you must create your own schema generator script. For FastAPI, you only need to specify the correct parameters in your pipeline configuration.
Example SHIELD Runner Acceptance pipeline:
yaml
resources:
repositories:
- repository: templates
type: git
name: Haskoning-Software-Development/pipeline_templates
trigger:
- dev
pool:
vmImage: "ubuntu-latest"
jobs:
- job: Deploy
displayName: Deploy job
steps:
- template: python/build_function_task_apim.yml@templates
parameters:
serviceConnection: $(serviceConnection)
storageAccountName: shieldrunneracceptance
appName: $(appName)
resourceGroupName: $(resourceGroupName)
apiManagementResourceGroupName: $(apiManagementResourceGroupName)
apiManagementServiceName: $(apiManagementServiceName)
apiServiceID: $(apiServiceID)
schemaGenerator: generate_schema_fastapi.py
fastapiAppImport: app.main:appIf your FastAPI app is located in a different folder or has a different name, update the fastapiAppImport parameter accordingly (e.g., myfolder.myapp:app).
Note: The description field in the exported OpenAPI schema is taken from the FastAPI application's description parameter, not from pyproject.toml.
Example of the FastAPI app definition:
python
from fastapi import FastAPI
app = FastAPI(
title="My API",
description="This is a sample API for demonstration purposes.",
version="1.0.0",
contact={"name": "Dirk Sliepenbeek", "email": "dirk.sliepenbeek@haskoning.com"}
)For more details, see the generate_schema_fastapi.py script.
2. FastAPI Function App Pipeline Details
From your existing app, the pipeline will:
- Install required libraries.
- Copy the schema generator script to
generate_schema.py. - Run
generate_schema.pyto generate theopenapi.jsonfile.
bash
poetry self add httpx poetry-plugin-export
python generate_schema.pyThe script uses FastAPI's TestClient to export the OpenAPI schema. Due to a bug in FastAPI, the generated schema is stuck at version 3.1 regardless of FastAPI config. The script automatically converts the schema to version 3.0.1 and adds the /openapi.json route for convenience.
Finally, the generated openapi.json file is imported into Azure API Management using your pipeline variables.