# apigenie-generator server fastapi

Source: https://apigenie.pl/docs/reference/generator/server-fastapi
Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md).
Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md).

[Tier 1](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification)

Generate a Python [FastAPI](https://fastapi.tiangolo.com) server from an OpenAPI document.

## Usage

```sh
apigenie-generator server fastapi [...OPTIONS] INPUT_FILE
```

## Description

The generated project has the layout of the `python-fastapi` generator of
[openapi-generator](https://openapi-generator.tech) and accepts its options, so a project generated
by openapi-generator can be generated again by API Genie. The input is an OpenAPI 3.0, 3.1 or 3.2
document or, since 0.12.0, a Swagger 2.0 document (see
[Swagger 2.0 input](/docs/reference/generator#swagger-20-input)); bundle a document that references
other files with `apigenie bundle` first. The code itself is written for FastAPI 0.115+,
pydantic 2.7+ and Python 3.10+:

```
pyproject.toml, requirements.txt, README.md, Dockerfile, docker-compose.yaml, openapi.yaml
src/openapi_server/
    main.py                 the application: includes the routers, loads the implementation
    apis/pets_api.py        the routes of the "pets" API (one module per tag)
    apis/pets_api_base.py   BasePetsApi: the methods to implement
    impl/__init__.py        the implementation package, yours
    models/                 pydantic models, one module per schema
    parameters.py           since 0.12.0, the decoding of delimited, deepObject and content
                            parameters, when there are any
    security_api.py         the dependencies checking credentials
    streaming.py            since 0.12.0, the reading and writing of streamed bodies, when
                            there are any
    webhooks.py             since 0.12.0, the webhooks of the API, when it has some
tests/                      pytest tests with FastAPI's TestClient
```

Routes validate requests, then call the methods of the base class of their API, which answer
501 Not Implemented. Implement them in a subclass, in a module of the implementation package:

```python
from openapi_server.apis.pets_api_base import BasePetsApi
from openapi_server.models import Pet


class PetsApi(BasePetsApi):
    async def show_pet_by_id(self, *, pet_id: str) -> Pet:
        return Pet(id=1, name="Rex")
```

The application imports the modules of the implementation package when it starts, and the first
subclass of a base class serves its requests. Tests can replace it with
`app.dependency_overrides[get_pets_api]`. Credentials are validated the same way, by a subclass of
`BaseSecurity` of `security_api.py`.

The generated code covers:

- routes with the status code, response class, documented responses (including `default`, ranges
  like `4XX` and headers), tags, summary, description, operation ID and deprecation of operations;
  routes of concrete paths come before the routes of templates matching them
- path, query, header and cookie parameters with their aliases, defaults and constraints. Since
  0.12.0, `pipeDelimited`, `spaceDelimited`, non-exploded `form` and header arrays are split
  into their items. `deepObject` query parameters, and parameters described with JSON `content`
  in a query, a header or a cookie, are validated into their models, with FastAPI's 422 errors
- JSON, text and binary request bodies, forms and file uploads (`UploadFile`)
- since 0.12.0, streams. A response whose only content is `text/event-stream`, JSON Lines
  (`application/jsonl`, `application/x-ndjson` and the like) or `application/json-seq` is
  streamed from the operation's method, which returns an `AsyncIterator` of the items. When the
  response has other content too, the items come from `<operation>_stream`, and they are
  streamed only when the `Accept` header names one of those media types before any other. In
  `text/event-stream`, each item is the `data` of an event, without an `id` or `event` field.
  JSON Lines and JSON text sequence request bodies reach the implementation as an
  `AsyncIterator` of validated items
- since 0.12.0, callbacks and webhooks as routes that the served OpenAPI document describes but
  the application doesn't serve, and response links in the documented responses
- since 0.12.0, operations marked `x-internal: true`, served but left out of the served OpenAPI
  document
- models: classes with aliases for names that aren't valid Python names, constraints, defaults and
  descriptions; enums; `allOf` merged into one class; `oneOf`/`anyOf` as unions, with discriminators
  where the document has them; nullable types of OpenAPI 3.0 and 3.1; recursive and mutually
  referencing models. Since 0.12.0: `prefixItems` as `tuple[...]` when the array has exactly one
  item per schema (`minItems`, and `items: false` or `maxItems`), lists of the union of the item
  schemas otherwise; `if`/`then`/`else`, `dependentRequired`, `dependentSchemas`, `not` and draft-07
  `dependencies` checked by a `model_validator` when they only test the presence and the values of
  properties; `unevaluatedProperties: false` rejecting unknown properties
- since 0.12.0, `readOnly` and `writeOnly`: a model with such properties, or referring to such a
  model, has an input variant for request bodies, e.g. `PetInput`, without the `readOnly`
  properties, and the model itself leaves the `writeOnly` ones out
- security: API keys (header, query, cookie), HTTP basic, bearer and other HTTP schemes, OAuth2
  (all flows, with scopes), OpenID Connect and, since 0.12.0, mutual TLS, with global security,
  alternatives (a request needs to meet one of the security requirements) and anonymous access
  (`{}`). For a `mutualTLS` scheme, `validate_<scheme>` of `BaseSecurity` (e.g.
  `validate_mutual_tls` for a scheme named `mutualTLS`) receives the client certificate as PEM.
  The ASGI server reports it in the `tls` extension of the request, and the value is `None`
  without one. Uvicorn reports none, so `validate_<scheme>` receives `None`: started with
  `--ssl-ca-certs` and `--ssl-cert-reqs 2`, Uvicorn refuses connections without a valid
  certificate itself

Files are generated again on every run, except the implementation package, the tests of the APIs,
`tests/conftest.py` and `.openapi-generator-ignore`, which are generated only when they don't
exist. Files listed in `.openapi-generator-ignore` (which uses the syntax of `.gitignore`) aren't
written. `.openapi-generator/FILES` lists the generated files, including the ones kept because they
exist, so generating again doesn't change it (since 0.12.0).

Differences from openapi-generator:

- routes declare their status code and response class, e.g. 201 or 204 without a body, instead of
  documenting every response as 200
- the implementation is one instance of the subclass, resolved by a FastAPI dependency, instead of
  an instance per request; the tokens of security schemes are passed to it
- models are idiomatic pydantic 2 models: `oneOf`/`anyOf` are unions (discriminated where
  possible) instead of wrapper classes, constraints use `pattern=` instead of the deprecated
  `regex=`, and there are no `to_dict()`/`from_dict()` helpers
- OAuth2 schemes of the same flow don't collide, and OpenID Connect schemes are supported
- since 0.12.0, mutual TLS security schemes are checked by the `validate_<scheme>` method of
  `BaseSecurity` instead of being left out
- unknown options are errors, not ignored

Constructs that FastAPI can't express are reported (object parameters and request bodies accepted
under one media type only as warnings, the others as information) and simplified: object
parameters other than `deepObject` query parameters are left out and the route receives the
request instead; arrays in paths and cookies are received as strings; parameters described with
`content` in a path, or with a media type other than JSON, are received as strings; nested objects
in forms are received as strings. A request body with a JSON or form media type next to JSON Lines
or `application/json-seq` is accepted as JSON or as the form only, because FastAPI decodes that
body before the route runs. The served OpenAPI document leaves out `deepObject` query parameters
and JSON `content` parameters, which dependencies in `parameters.py` read from the request,
describes delimited arrays without their style, and leaves mutual TLS out.

## Extensions

| Extension | Effect |
| --------- | ------ |
| `x-apigenie.codegen.controller-name` | on an operation or its path item: the API module of the operation, instead of its first tag |
| `x-apigenie.codegen.action-name` | name of the function of an operation, instead of its `operationId` |
| `x-apigenie.codegen.disabled` | `true` on an operation or its path item leaves the operation out, with `skipDisabled` |
| `x-internal` | since 0.12.0, `true` on an operation or its path item leaves the operation out of the served OpenAPI document; the route is still served |
| `x-codegen-request-body-name` | on an operation or its request body: the name of the body parameter |
| `x-defaultMapping` | `defaultMapping` of a discriminator in OpenAPI 3.0 and 3.1 documents: the schema of the values whose discriminator value isn't mapped |

The extensions can live in an overlay for this target instead of in the document, e.g.
`fastapi.overlay.yaml`:

```yaml
overlay: 1.0.0
info:
  title: FastAPI names
  version: 1.0.0
actions:
  - target: $.paths['/pets'].post
    update:
      x-codegen-request-body-name: pet
      x-apigenie:
        codegen:
          action-name: add_pet
```

```sh
apigenie-generator server fastapi openapi.yaml --overlay fastapi.overlay.yaml -o out
```

## Options

### -c, --config

Path to the configuration file to use. See the "Configuration" section for more information.

### --overlay OVERLAY

Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the
extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those
listed under `commands.generate.server_fastapi.overlay` in the configuration file (with paths
relative to it). Warnings and errors about a value an overlay set point to the overlay.

### --strict

Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated)
instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`).

### --check

Writes nothing: compares what the generator would write with the output directory, prints the
files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See
[Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date).

### -o, --output

Directory where the project is generated.

### --package-name

Python package of the generated code (`packageName`), e.g. `pet_store` or `acme.pet_store`.
Defaults to `openapi_server`.

### --package-version

Version of the generated project (`packageVersion`). Defaults to the version of the API when pip
accepts it, otherwise to `1.0.0`.

### -p, --property NAME=VALUE

Sets a generator option (see below), e.g. `-p serverPort=8000`. Options given on the command line
take precedence over the configuration file. Mapping options take comma-separated lists, e.g.
`-p 'nameMappings=_links=links,$type=kind'`.

## Configuration

Options can also be set in the configuration file, either directly or in an
`additionalProperties` section, like in configuration files of openapi-generator:

```yaml
version: '1.0'
commands:
  generate:
    server_fastapi:
      packageName: pet_store
      serverPort: 8000
      nameMappings:
        _links: links
```

| Option | Description |
| ------ | ----------- |
| `packageName` | Python package of the generated code (default `openapi_server`) |
| `packageVersion` | Version of the project (defaults to the version of the API when pip accepts it, otherwise `1.0.0`) |
| `serverPort` | Port the server listens to (defaults to the port of the first server, or 8080) |
| `sourceFolder` | Directory of the package, relative to the output directory (default `src`) |
| `fastapiImplementationPackage` | Package of the implementation of the APIs (default `impl`), inside the generated package unless useExternalImplementationPackage is set |
| `useExternalImplementationPackage` | The implementation package is outside the generated package and isn't generated (default `false`) |
| `generateTests` | Generate tests (tests/) (default `true`) |
| `generateDocker` | Generate a Dockerfile and docker-compose.yaml (default `true`) |
| `generatorVersion` | Version of the generator written into generated files |
| `sortParamsByRequiredFlag` | Put required parameters before optional ones (default `true`) |
| `skipDeprecated` | Don't generate code for deprecated operations (default `false`) |
| `skipDisabled` | Don't generate code for operations disabled with x-apigenie (default `false`) |
| `modelsLayout` | Where models are written: `modules` (a module per model, the default) or `single` (one module) |
| `disallowAdditionalPropertiesIfNotPresent` | Models of schemas without additionalProperties reject unknown properties (extra="forbid") (default `false`) |
| `hideGenerationTimestamp` | Accepted for compatibility with openapi-generator; generated files have no timestamps |
| `modelNamePrefix` | Prefix of model names |
| `modelNameSuffix` | Suffix of model names |
| `modelNameMappings` | Mappings of schema names to model names (Schema=Model,...) |
| `nameMappings` | Mappings of property names to field names (name=field_name,...) |
| `parameterNameMappings` | Mappings of parameter names to Python names (name=python_name,...) |
| `enumNameMappings` | Mappings of enum values to member names (value=NAME,...) |

## Verification

The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express OpenAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#openapi).

This target's support tier is [Tier 1](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, with the goal of supporting every feature of the fixture. Its unsupported features are worked on first.

| Results | Level 1 | Level 2 | Level 3 |
| --- | --- | --- | --- |
| Release 0.12.0 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 39 supported, 0 not yet | ✓ pass (python 3.12.11 fastapi 0.142.2 pydantic 2.13.5 mypy 2.4.0, ruff 0.16.10) | ✓ 72 of 77 operations pass (python) |
| Development version | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 39 supported, 0 not yet | runs before a release | runs before a release |
