fastapi-code-generator


Namefastapi-code-generator JSON
Version 0.5.1 PyPI version JSON
download
home_pagehttps://github.com/koxudaxi/fastapi-code-generator
SummaryNone
upload_time2024-07-02 14:26:28
maintainerNone
docs_urlNone
authorKoudai Aono
requires_python<4.0.0,>=3.8.0
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # fastapi-code-generator

This code generator creates a FastAPI app from an openapi file.

[![PyPI version](https://badge.fury.io/py/fastapi-code-generator.svg)](https://pypi.python.org/pypi/fastapi-code-generator)
[![Downloads](https://pepy.tech/badge/fastapi-code-generator/month)](https://pepy.tech/project/fastapi-code-generator)
[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/fastapi-code-generator)](https://pypi.python.org/pypi/fastapi-code-generator)
[![codecov](https://codecov.io/gh/koxudaxi/fastapi-code-generator/branch/master/graph/badge.svg)](https://codecov.io/gh/koxudaxi/fastapi-code-generator)
![license](https://img.shields.io/github/license/koxudaxi/fastapi-code-generator.svg)
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)


## This project is in experimental phase.

fastapi-code-generator uses [datamodel-code-generator](https://github.com/koxudaxi/datamodel-code-generator) to generate pydantic models

## Help
See [documentation](https://koxudaxi.github.io/fastapi-code-generator) for more details.


## Installation

To install `fastapi-code-generator`:
```sh
$ pip install fastapi-code-generator
```

## Usage

The `fastapi-code-generator` command:
```
Usage: fastapi-codegen [OPTIONS]

Options:
  -i, --input FILENAME     [required]
  -o, --output PATH        [required]
  -t, --template-dir PATH
  -m, --model-file         Specify generated model file path + name, if not default to models.py
  -r, --generate-routers   Generate modular api with multiple routers using RouterAPI (for bigger applications).
  --specify-tags           Use along with --generate-routers to generate specific routers from given list of tags.
  -c, --custom-visitors    PATH - A custom visitor that adds variables to the template.
  -d, --output-model-type  Specify a Pydantic base model to use (see [datamodel-code-generator](https://github.com/koxudaxi/datamodel-code-generator); default is `pydantic.BaseModel`).
  -p, --python-version     Specify a Python version to target (default is `3.8`).
  --install-completion     Install completion for the current shell.
  --show-completion        Show completion for the current shell, to copy it
                           or customize the installation.
  --help                   Show this message and exit.
```

### Pydantic 2 support

Specify the Pydantic 2 `BaseModel` version in the command line, for example:

```sh
$ fastapi-codegen --input api.yaml --output app --output-model-type pydantic_v2.BaseModel
```

## Example
### OpenAPI
```sh
$ fastapi-codegen --input api.yaml --output app
```

<details>
<summary>api.yaml</summary>
<pre>
<code>
openapi: "3.0.0"
info:
  version: 1.0.0
  title: Swagger Petstore
  license:
    name: MIT
servers:
  - url: http://petstore.swagger.io/v1
paths:
  /pets:
    get:
      summary: List all pets
      operationId: listPets
      tags:
        - pets
      parameters:
        - name: limit
          in: query
          description: How many items to return at one time (max 100)
          required: false
          schema:
            type: integer
            format: int32
      responses:
        '200':
          description: A paged array of pets
          headers:
            x-next:
              description: A link to the next page of responses
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Pets"
        default:
          description: unexpected error
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
                x-amazon-apigateway-integration:
                  uri:
                    Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations
                  passthroughBehavior: when_no_templates
                  httpMethod: POST
                  type: aws_proxy
    post:
      summary: Create a pet
      operationId: createPets
      tags:
        - pets
      responses:
        '201':
          description: Null response
        default:
          description: unexpected error
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
                x-amazon-apigateway-integration:
                  uri:
                    Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations
                  passthroughBehavior: when_no_templates
                  httpMethod: POST
                  type: aws_proxy
  /pets/{petId}:
    get:
      summary: Info for a specific pet
      operationId: showPetById
      tags:
        - pets
      parameters:
        - name: petId
          in: path
          required: true
          description: The id of the pet to retrieve
          schema:
            type: string
      responses:
        '200':
          description: Expected response to a valid request
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Pets"
        default:
          description: unexpected error
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
    x-amazon-apigateway-integration:
      uri:
        Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations
      passthroughBehavior: when_no_templates
      httpMethod: POST
      type: aws_proxy
components:
  schemas:
    Pet:
      required:
        - id
        - name
      properties:
        id:
          type: integer
          format: int64
        name:
          type: string
        tag:
          type: string
    Pets:
      type: array
      description: list of pet
      items:
        $ref: "#/components/schemas/Pet"
    Error:
      required:
        - code
        - message
      properties:
        code:
          type: integer
          format: int32
        message:
          type: string
</code>
</pre>
</details>


`app/main.py`:
```python
# generated by fastapi-codegen:
#   filename:  api.yaml
#   timestamp: 2020-06-14T10:45:22+00:00

from __future__ import annotations

from typing import Optional

from fastapi import FastAPI, Query

from .models import Pets

app = FastAPI(version="1.0.0", title="Swagger Petstore", license="{'name': 'MIT'}",)


@app.get('/pets', response_model=Pets)
def list_pets(limit: Optional[int] = None) -> Pets:
    """
    List all pets
    """
    pass


@app.post('/pets', response_model=None)
def create_pets() -> None:
    """
    Create a pet
    """
    pass


@app.get('/pets/{pet_id}', response_model=Pets)
def show_pet_by_id(pet_id: str = Query(..., alias='petId')) -> Pets:
    """
    Info for a specific pet
    """
    pass

```

`app/models.py`:
```python
# generated by datamodel-codegen:
#   filename:  api.yaml
#   timestamp: 2020-06-14T10:45:22+00:00

from typing import List, Optional

from pydantic import BaseModel, Field


class Pet(BaseModel):
    id: int
    name: str
    tag: Optional[str] = None


class Pets(BaseModel):
    __root__: List[Pet] = Field(..., description='list of pet')


class Error(BaseModel):
    code: int
    message: str
```

## Custom Template
If you want to generate custom `*.py` files then you can give a custom template directory to fastapi-code-generator with `-t` or `--template-dir` options of the command.

fastapi-code-generator will search for [jinja2](https://jinja.palletsprojects.com/) template files in given template directory, for example `some_jinja_templates/list_pets.py`.

```bash
fastapi-code-generator --template-dir some_jinja_templates --output app --input api.yaml
```

These files will be rendered and written to the output directory. Also, the generated file names will be created with the template name and extension of `*.py`, for example `app/list_pets.py` will be a separate file generated from the jinja template alongside the default `app/main.py`

### Variables
You can use the following variables in the jinja2 templates

- `imports`  all imports statements
- `info`  all info statements
- `operations` `operations` is list of `operation`
  - `operation.type` HTTP METHOD
  - `operation.path` Path
  - `operation.snake_case_path` Snake-cased Path
  - `operation.response` response object
  - `operation.function_name` function name is created `operationId` or `METHOD` + `Path` 
  - `operation.snake_case_arguments` Snake-cased function arguments
  - `operation.security` [Security](https://swagger.io/docs/specification/authentication/)
  - `operation.summary` a summary
  - `operation.tags` [Tags](https://swagger.io/docs/specification/grouping-operations-with-tags/)

### default template 
`main.jinja2`
```jinja2
from __future__ import annotations

from fastapi import FastAPI

{{imports}}

app = FastAPI(
    {% if info %}
    {% for key,value in info.items() %}
    {{ key }} = "{{ value }}",
    {% endfor %}
    {% endif %}
    )


{% for operation in operations %}
@app.{{operation.type}}('{{operation.snake_case_path}}', response_model={{operation.response}})
def {{operation.function_name}}({{operation.snake_case_arguments}}) -> {{operation.response}}:
    {%- if operation.summary %}
    """
    {{ operation.summary }}
    """
    {%- endif %}
    pass
{% endfor %}

```

### modular template
`modular_template/main.jinja2`:
```jinja
from __future__ import annotations

from fastapi import FastAPI

from .routers import {{ routers | join(", ") }}

app = FastAPI(
    {% if info %}
    {% for key,value in info.items() %}
    {% set info_value= value.__repr__() %}
    {{ key }} = {{info_value}},
    {% endfor %}
    {% endif %}
    )

{% for router in routers -%}
app.include_router({{router}}.router)
{% endfor -%}

@app.get("/")
async def root():
    return {"message": "Gateway of the App"}
```

`modular_template/routers.jinja2`:
```jinja
from __future__ import annotations

from fastapi import APIRouter
from fastapi import FastAPI

from ..dependencies import *

router = APIRouter(
    tags=['{{tag}}']
    )

{% for operation in operations %}
{% if operation.tags[0] == tag %}
@router.{{operation.type}}('{{operation.snake_case_path}}', response_model={{operation.response}}
    {% if operation.additional_responses %}
        , responses={
            {% for status_code, models in operation.additional_responses.items() %}
                '{{ status_code }}': {
                {% for key, model in models.items() %}
                    '{{ key }}': {{ model }}{% if not loop.last %},{% endif %}
                {% endfor %}
                }{% if not loop.last %},{% endif %}
            {% endfor %}
        }
    {% endif %}
    {% if operation.tags%}
    , tags={{operation.tags}}
    {% endif %})
def {{operation.function_name}}({{operation.snake_case_arguments}}) -> {{operation.return_type}}:
    {%- if operation.summary %}
    """
    {{ operation.summary }}
    """
    {%- endif %}
    pass
{% endif %}
{% endfor %}
```

`modular_template/dependencies.jinja2`:
```jinja
{{imports}}
```

## Custom Visitors

Custom visitors allow you to pass custom variables to your custom templates.

E.g.

### custom template
`custom-template.jinja2`
```jinja2
#{ % custom_header %}
from __future__ import annotations

from fastapi import FastAPI

...
```

### custom visitor
`custom-visitor.py`
```python
from typing import Dict, Optional

from fastapi_code_generator.parser import OpenAPIParser
from fastapi_code_generator.visitor import Visitor


def custom_visitor(parser: OpenAPIParser, model_path: Path) -> Dict[str, object]:
    return {'custom_header': 'My header'}


visit: Visitor = custom_visitor
```

### Multiple Files using APIRouter (For Bigger Applications)

```
├── app                      # "app" is a Root directory      
│   ├── main.py              # "main" module
│   ├── models.py            # "models" of the application
│   ├── dependencies.py      # "dependencies" module, e.g. import app.dependencies
│   └── routers              # "routers" is a "app subpackage"
│       ├── fat_cats.py      # "fat_cats" submodule, e.g. import app.routers.fat_cats
│       ├── slim_dogs.py     # "slim_dogs" submodule, e.g. import app.routers.slim_dogs
│       └── wild_boars.py    # "wild_boars" submodule, e.g. import app.routers.wild_boars
```

See [documentation](https://fastapi.tiangolo.com/tutorial/bigger-applications/) of APIRouter OpenAPI for more details.

**_Generate main aside with all of its routers_**:
```bash
$ fastapi-codegen --input swagger.yaml --output app --generate-routers
```

**_Regenerate specific routers_**:
```bash
$ fastapi-codegen --input swagger.yaml --output app --generate-routers --specify-tags "Wild Boars, Fat Cats"
```


<details>
<summary>swagger.yaml</summary>
<pre>
<code>
openapi: "3.0.0"
info:
  version: 1.0.0
  title: Swagger Petstore
  license:
    name: MIT
servers:
  - url: /
  - url: http://petstore.swagger.io/v1
  - url: http://localhost:8080/
paths:
  /boars:
    get:
      summary: List All Wild Boars
      operationId: listWildBoars
      tags:
        - Wild Boars
      parameters:
        - name: limit
          in: query
          description: How many items to return at one time (max 100)
          required: false
          schema:
            type: integer
      responses:
        '200':
          description: An array of wild boars
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/WildBoars"
    post:
      summary: Create a Wild Boar
      operationId: createWildBoars
      tags:
        - Wild Boars
      responses:
        '201':
          description: Null response
  /boars/{boarId}:
    get:
      summary: Info For a Specific Boar
      operationId: showBoarById
      tags:
        - Wild Boars
      parameters:
        - name: boarId
          in: path
          required: true
          description: The id of the boar to retrieve
          schema:
            type: string
      responses:
        '200':
          description: Expected response to a valid request
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Pet"
  /cats:
    get:
      summary: List All Fat Cats
      operationId: listFatCats
      tags:
        - Fat Cats
      parameters:
        - name: limit
          in: query
          description: How many items to return at one time (max 100)
          required: false
          schema:
            type: integer
      responses:
        '200':
          description: An array of fat cats
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/FatCats"
    post:
      summary: Create a Fat Cat
      operationId: createFatCats
      tags:
        - Fat Cats
      responses:
        '201':
          description: Null response
  /cats/{catId}:
    get:
      summary: Info For a Specific Cat
      operationId: showCatById
      tags:
        - Fat Cats
      parameters:
        - name: catId
          in: path
          required: true
          description: The id of the cat to retrieve
          schema:
            type: string
      responses:
        '200':
          description: Expected response to a valid request
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Pet"
  /dogs:
    get:
      summary: List All Slim Dogs
      operationId: listSlimDogs
      tags:
        - Slim Dogs
      parameters:
        - name: limit
          in: query
          description: How many items to return at one time (max 100)
          required: false
          schema:
            type: integer
      responses:
        '200':
          description: An array of slim dogs
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SlimDogs"
    post:
      summary: Create a Slim Dog
      operationId: createSlimDogs
      tags:
        - Slim Dogs
      responses:
        '201':
          description: Null response
  /dogs/{dogId}:
    get:
      summary: Info For a Specific Dog
      operationId: showDogById
      tags:
        - Slim Dogs
      parameters:
        - name: dogId
          in: path
          required: true
          description: The id of the dog to retrieve
          schema:
            type: string
      responses:
        '200':
          description: Expected response to a valid request
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Pet"
components:
  schemas:
    Pet:
      required:
        - id
        - name
      properties:
        id:
          type: integer
        name:
          type: string
        tag:
          type: string
    FatCats:
      type: array
      description: list of fat cats
      items:
        $ref: "#/components/schemas/Pet"
    SlimDogs:
      type: array
      description: list of slim dogs
      items:
        $ref: "#/components/schemas/Pet"
    WildBoars:
      type: array
      description: list of wild boars
      items:
        $ref: "#/components/schemas/Pet"
</code>
</pre>
</details>

`app/main.py`:

```python
# generated by fastapi-codegen:
#   filename:  swagger.yaml
#   timestamp: 2023-04-04T12:06:16+00:00

from __future__ import annotations

from fastapi import FastAPI

from .routers import fat_cats, slim_dogs, wild_boars

app = FastAPI(
    version='1.0.0',
    title='Swagger Petstore',
    license={'name': 'MIT'},
    servers=[
        {'url': '/'},
        {'url': 'http://petstore.swagger.io/v1'},
        {'url': 'http://localhost:8080/'},
    ],
)

app.include_router(fat_cats.router)
app.include_router(slim_dogs.router)
app.include_router(wild_boars.router)


@app.get("/")
async def root():
    return {"message": "Gateway of the App"}
```

`app/models.py`:

```python
# generated by fastapi-codegen:
#   filename:  swagger.yaml
#   timestamp: 2023-04-04T12:06:16+00:00

from __future__ import annotations

from typing import List, Optional

from pydantic import BaseModel, Field


class Pet(BaseModel):
    id: int
    name: str
    tag: Optional[str] = None


class FatCats(BaseModel):
    __root__: List[Pet] = Field(..., description='list of fat cats')


class SlimDogs(BaseModel):
    __root__: List[Pet] = Field(..., description='list of slim dogs')


class WildBoars(BaseModel):
    __root__: List[Pet] = Field(..., description='list of wild boars')
```

`app/routers/fat_cats.py`:

```python
# generated by fastapi-codegen:
#   filename:  swagger.yaml
#   timestamp: 2023-04-04T12:06:16+00:00

from __future__ import annotations

from fastapi import APIRouter

from ..dependencies import *

router = APIRouter(tags=['Fat Cats'])


@router.get('/cats', response_model=FatCats, tags=['Fat Cats'])
def list_fat_cats(limit: Optional[int] = None) -> FatCats:
    """
    List All Fat Cats
    """
    pass


@router.post('/cats', response_model=None, tags=['Fat Cats'])
def create_fat_cats() -> None:
    """
    Create a Fat Cat
    """
    pass


@router.get('/cats/{cat_id}', response_model=Pet, tags=['Fat Cats'])
def show_cat_by_id(cat_id: str = Path(..., alias='catId')) -> Pet:
    """
    Info For a Specific Cat
    """
    pass
```

`app/routers/slim_dogs.py`:

```python
# generated by fastapi-codegen:
#   filename:  swagger.yaml
#   timestamp: 2023-04-04T12:06:16+00:00

from __future__ import annotations

from fastapi import APIRouter

from ..dependencies import *

router = APIRouter(tags=['Slim Dogs'])


@router.get('/dogs', response_model=SlimDogs, tags=['Slim Dogs'])
def list_slim_dogs(limit: Optional[int] = None) -> SlimDogs:
    """
    List All Slim Dogs
    """
    pass


@router.post('/dogs', response_model=None, tags=['Slim Dogs'])
def create_slim_dogs() -> None:
    """
    Create a Slim Dog
    """
    pass


@router.get('/dogs/{dog_id}', response_model=Pet, tags=['Slim Dogs'])
def show_dog_by_id(dog_id: str = Path(..., alias='dogId')) -> Pet:
    """
    Info For a Specific Dog
    """
    pass
```

`app/routers/wild_boars.py`:

```python
# generated by fastapi-codegen:
#   filename:  swagger.yaml
#   timestamp: 2023-04-04T12:06:16+00:00

from __future__ import annotations

from fastapi import APIRouter

from ..dependencies import *

router = APIRouter(tags=['Wild Boars'])


@router.get('/boars', response_model=WildBoars, tags=['Wild Boars'])
def list_wild_boars(limit: Optional[int] = None) -> WildBoars:
    """
    List All Wild Boars
    """
    pass


@router.post('/boars', response_model=None, tags=['Wild Boars'])
def create_wild_boars() -> None:
    """
    Create a Wild Boar
    """
    pass


@router.get('/boars/{boar_id}', response_model=Pet, tags=['Wild Boars'])
def show_boar_by_id(boar_id: str = Path(..., alias='boarId')) -> Pet:
    """
    Info For a Specific Boar
    """
    pass
```

`app/dependencies.py`:

```python
# generated by fastapi-codegen:
#   filename:  swagger.yaml
#   timestamp: 2023-04-04T12:06:16+00:00

from __future__ import annotations

from typing import Optional

from fastapi import Path

from .models import FatCats, Pet, SlimDogs, WildBoars
```
## PyPi 

[https://pypi.org/project/fastapi-code-generator](https://pypi.org/project/fastapi-code-generator)

## License

fastapi-code-generator is released under the MIT License. http://www.opensource.org/licenses/mit-license



            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/koxudaxi/fastapi-code-generator",
    "name": "fastapi-code-generator",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<4.0.0,>=3.8.0",
    "maintainer_email": null,
    "keywords": null,
    "author": "Koudai Aono",
    "author_email": "koxudaxi@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/ad/2d/2bddf102e4d48cf7b56e246bf1a51672abe18b922a326522d119a866df6d/fastapi_code_generator-0.5.1.tar.gz",
    "platform": null,
    "description": "# fastapi-code-generator\n\nThis code generator creates a FastAPI app from an openapi file.\n\n[![PyPI version](https://badge.fury.io/py/fastapi-code-generator.svg)](https://pypi.python.org/pypi/fastapi-code-generator)\n[![Downloads](https://pepy.tech/badge/fastapi-code-generator/month)](https://pepy.tech/project/fastapi-code-generator)\n[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/fastapi-code-generator)](https://pypi.python.org/pypi/fastapi-code-generator)\n[![codecov](https://codecov.io/gh/koxudaxi/fastapi-code-generator/branch/master/graph/badge.svg)](https://codecov.io/gh/koxudaxi/fastapi-code-generator)\n![license](https://img.shields.io/github/license/koxudaxi/fastapi-code-generator.svg)\n[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)\n\n\n## This project is in experimental phase.\n\nfastapi-code-generator uses [datamodel-code-generator](https://github.com/koxudaxi/datamodel-code-generator) to generate pydantic models\n\n## Help\nSee [documentation](https://koxudaxi.github.io/fastapi-code-generator) for more details.\n\n\n## Installation\n\nTo install `fastapi-code-generator`:\n```sh\n$ pip install fastapi-code-generator\n```\n\n## Usage\n\nThe `fastapi-code-generator` command:\n```\nUsage: fastapi-codegen [OPTIONS]\n\nOptions:\n  -i, --input FILENAME     [required]\n  -o, --output PATH        [required]\n  -t, --template-dir PATH\n  -m, --model-file         Specify generated model file path + name, if not default to models.py\n  -r, --generate-routers   Generate modular api with multiple routers using RouterAPI (for bigger applications).\n  --specify-tags           Use along with --generate-routers to generate specific routers from given list of tags.\n  -c, --custom-visitors    PATH - A custom visitor that adds variables to the template.\n  -d, --output-model-type  Specify a Pydantic base model to use (see [datamodel-code-generator](https://github.com/koxudaxi/datamodel-code-generator); default is `pydantic.BaseModel`).\n  -p, --python-version     Specify a Python version to target (default is `3.8`).\n  --install-completion     Install completion for the current shell.\n  --show-completion        Show completion for the current shell, to copy it\n                           or customize the installation.\n  --help                   Show this message and exit.\n```\n\n### Pydantic 2 support\n\nSpecify the Pydantic 2 `BaseModel` version in the command line, for example:\n\n```sh\n$ fastapi-codegen --input api.yaml --output app --output-model-type pydantic_v2.BaseModel\n```\n\n## Example\n### OpenAPI\n```sh\n$ fastapi-codegen --input api.yaml --output app\n```\n\n<details>\n<summary>api.yaml</summary>\n<pre>\n<code>\nopenapi: \"3.0.0\"\ninfo:\n  version: 1.0.0\n  title: Swagger Petstore\n  license:\n    name: MIT\nservers:\n  - url: http://petstore.swagger.io/v1\npaths:\n  /pets:\n    get:\n      summary: List all pets\n      operationId: listPets\n      tags:\n        - pets\n      parameters:\n        - name: limit\n          in: query\n          description: How many items to return at one time (max 100)\n          required: false\n          schema:\n            type: integer\n            format: int32\n      responses:\n        '200':\n          description: A paged array of pets\n          headers:\n            x-next:\n              description: A link to the next page of responses\n              schema:\n                type: string\n          content:\n            application/json:\n              schema:\n                $ref: \"#/components/schemas/Pets\"\n        default:\n          description: unexpected error\n          content:\n            application/json:\n              schema:\n                $ref: \"#/components/schemas/Error\"\n                x-amazon-apigateway-integration:\n                  uri:\n                    Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations\n                  passthroughBehavior: when_no_templates\n                  httpMethod: POST\n                  type: aws_proxy\n    post:\n      summary: Create a pet\n      operationId: createPets\n      tags:\n        - pets\n      responses:\n        '201':\n          description: Null response\n        default:\n          description: unexpected error\n          content:\n            application/json:\n              schema:\n                $ref: \"#/components/schemas/Error\"\n                x-amazon-apigateway-integration:\n                  uri:\n                    Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations\n                  passthroughBehavior: when_no_templates\n                  httpMethod: POST\n                  type: aws_proxy\n  /pets/{petId}:\n    get:\n      summary: Info for a specific pet\n      operationId: showPetById\n      tags:\n        - pets\n      parameters:\n        - name: petId\n          in: path\n          required: true\n          description: The id of the pet to retrieve\n          schema:\n            type: string\n      responses:\n        '200':\n          description: Expected response to a valid request\n          content:\n            application/json:\n              schema:\n                $ref: \"#/components/schemas/Pets\"\n        default:\n          description: unexpected error\n          content:\n            application/json:\n              schema:\n                $ref: \"#/components/schemas/Error\"\n    x-amazon-apigateway-integration:\n      uri:\n        Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations\n      passthroughBehavior: when_no_templates\n      httpMethod: POST\n      type: aws_proxy\ncomponents:\n  schemas:\n    Pet:\n      required:\n        - id\n        - name\n      properties:\n        id:\n          type: integer\n          format: int64\n        name:\n          type: string\n        tag:\n          type: string\n    Pets:\n      type: array\n      description: list of pet\n      items:\n        $ref: \"#/components/schemas/Pet\"\n    Error:\n      required:\n        - code\n        - message\n      properties:\n        code:\n          type: integer\n          format: int32\n        message:\n          type: string\n</code>\n</pre>\n</details>\n\n\n`app/main.py`:\n```python\n# generated by fastapi-codegen:\n#   filename:  api.yaml\n#   timestamp: 2020-06-14T10:45:22+00:00\n\nfrom __future__ import annotations\n\nfrom typing import Optional\n\nfrom fastapi import FastAPI, Query\n\nfrom .models import Pets\n\napp = FastAPI(version=\"1.0.0\", title=\"Swagger Petstore\", license=\"{'name': 'MIT'}\",)\n\n\n@app.get('/pets', response_model=Pets)\ndef list_pets(limit: Optional[int] = None) -> Pets:\n    \"\"\"\n    List all pets\n    \"\"\"\n    pass\n\n\n@app.post('/pets', response_model=None)\ndef create_pets() -> None:\n    \"\"\"\n    Create a pet\n    \"\"\"\n    pass\n\n\n@app.get('/pets/{pet_id}', response_model=Pets)\ndef show_pet_by_id(pet_id: str = Query(..., alias='petId')) -> Pets:\n    \"\"\"\n    Info for a specific pet\n    \"\"\"\n    pass\n\n```\n\n`app/models.py`:\n```python\n# generated by datamodel-codegen:\n#   filename:  api.yaml\n#   timestamp: 2020-06-14T10:45:22+00:00\n\nfrom typing import List, Optional\n\nfrom pydantic import BaseModel, Field\n\n\nclass Pet(BaseModel):\n    id: int\n    name: str\n    tag: Optional[str] = None\n\n\nclass Pets(BaseModel):\n    __root__: List[Pet] = Field(..., description='list of pet')\n\n\nclass Error(BaseModel):\n    code: int\n    message: str\n```\n\n## Custom Template\nIf you want to generate custom `*.py` files then you can give a custom template directory to fastapi-code-generator with `-t` or `--template-dir` options of the command.\n\nfastapi-code-generator will search for [jinja2](https://jinja.palletsprojects.com/) template files in given template directory, for example `some_jinja_templates/list_pets.py`.\n\n```bash\nfastapi-code-generator --template-dir some_jinja_templates --output app --input api.yaml\n```\n\nThese files will be rendered and written to the output directory. Also, the generated file names will be created with the template name and extension of `*.py`, for example `app/list_pets.py` will be a separate file generated from the jinja template alongside the default `app/main.py`\n\n### Variables\nYou can use the following variables in the jinja2 templates\n\n- `imports`  all imports statements\n- `info`  all info statements\n- `operations` `operations` is list of `operation`\n  - `operation.type` HTTP METHOD\n  - `operation.path` Path\n  - `operation.snake_case_path` Snake-cased Path\n  - `operation.response` response object\n  - `operation.function_name` function name is created `operationId` or `METHOD` + `Path` \n  - `operation.snake_case_arguments` Snake-cased function arguments\n  - `operation.security` [Security](https://swagger.io/docs/specification/authentication/)\n  - `operation.summary` a summary\n  - `operation.tags` [Tags](https://swagger.io/docs/specification/grouping-operations-with-tags/)\n\n### default template \n`main.jinja2`\n```jinja2\nfrom __future__ import annotations\n\nfrom fastapi import FastAPI\n\n{{imports}}\n\napp = FastAPI(\n    {% if info %}\n    {% for key,value in info.items() %}\n    {{ key }} = \"{{ value }}\",\n    {% endfor %}\n    {% endif %}\n    )\n\n\n{% for operation in operations %}\n@app.{{operation.type}}('{{operation.snake_case_path}}', response_model={{operation.response}})\ndef {{operation.function_name}}({{operation.snake_case_arguments}}) -> {{operation.response}}:\n    {%- if operation.summary %}\n    \"\"\"\n    {{ operation.summary }}\n    \"\"\"\n    {%- endif %}\n    pass\n{% endfor %}\n\n```\n\n### modular template\n`modular_template/main.jinja2`:\n```jinja\nfrom __future__ import annotations\n\nfrom fastapi import FastAPI\n\nfrom .routers import {{ routers | join(\", \") }}\n\napp = FastAPI(\n    {% if info %}\n    {% for key,value in info.items() %}\n    {% set info_value= value.__repr__() %}\n    {{ key }} = {{info_value}},\n    {% endfor %}\n    {% endif %}\n    )\n\n{% for router in routers -%}\napp.include_router({{router}}.router)\n{% endfor -%}\n\n@app.get(\"/\")\nasync def root():\n    return {\"message\": \"Gateway of the App\"}\n```\n\n`modular_template/routers.jinja2`:\n```jinja\nfrom __future__ import annotations\n\nfrom fastapi import APIRouter\nfrom fastapi import FastAPI\n\nfrom ..dependencies import *\n\nrouter = APIRouter(\n    tags=['{{tag}}']\n    )\n\n{% for operation in operations %}\n{% if operation.tags[0] == tag %}\n@router.{{operation.type}}('{{operation.snake_case_path}}', response_model={{operation.response}}\n    {% if operation.additional_responses %}\n        , responses={\n            {% for status_code, models in operation.additional_responses.items() %}\n                '{{ status_code }}': {\n                {% for key, model in models.items() %}\n                    '{{ key }}': {{ model }}{% if not loop.last %},{% endif %}\n                {% endfor %}\n                }{% if not loop.last %},{% endif %}\n            {% endfor %}\n        }\n    {% endif %}\n    {% if operation.tags%}\n    , tags={{operation.tags}}\n    {% endif %})\ndef {{operation.function_name}}({{operation.snake_case_arguments}}) -> {{operation.return_type}}:\n    {%- if operation.summary %}\n    \"\"\"\n    {{ operation.summary }}\n    \"\"\"\n    {%- endif %}\n    pass\n{% endif %}\n{% endfor %}\n```\n\n`modular_template/dependencies.jinja2`:\n```jinja\n{{imports}}\n```\n\n## Custom Visitors\n\nCustom visitors allow you to pass custom variables to your custom templates.\n\nE.g.\n\n### custom template\n`custom-template.jinja2`\n```jinja2\n#{ % custom_header %}\nfrom __future__ import annotations\n\nfrom fastapi import FastAPI\n\n...\n```\n\n### custom visitor\n`custom-visitor.py`\n```python\nfrom typing import Dict, Optional\n\nfrom fastapi_code_generator.parser import OpenAPIParser\nfrom fastapi_code_generator.visitor import Visitor\n\n\ndef custom_visitor(parser: OpenAPIParser, model_path: Path) -> Dict[str, object]:\n    return {'custom_header': 'My header'}\n\n\nvisit: Visitor = custom_visitor\n```\n\n### Multiple Files using APIRouter (For Bigger Applications)\n\n```\n\u251c\u2500\u2500 app                      # \"app\" is a Root directory      \n\u2502   \u251c\u2500\u2500 main.py              # \"main\" module\n\u2502   \u251c\u2500\u2500 models.py            # \"models\" of the application\n\u2502   \u251c\u2500\u2500 dependencies.py      # \"dependencies\" module, e.g. import app.dependencies\n\u2502   \u2514\u2500\u2500 routers              # \"routers\" is a \"app subpackage\"\n\u2502       \u251c\u2500\u2500 fat_cats.py      # \"fat_cats\" submodule, e.g. import app.routers.fat_cats\n\u2502       \u251c\u2500\u2500 slim_dogs.py     # \"slim_dogs\" submodule, e.g. import app.routers.slim_dogs\n\u2502       \u2514\u2500\u2500 wild_boars.py    # \"wild_boars\" submodule, e.g. import app.routers.wild_boars\n```\n\nSee [documentation](https://fastapi.tiangolo.com/tutorial/bigger-applications/) of APIRouter OpenAPI for more details.\n\n**_Generate main aside with all of its routers_**:\n```bash\n$ fastapi-codegen --input swagger.yaml --output app --generate-routers\n```\n\n**_Regenerate specific routers_**:\n```bash\n$ fastapi-codegen --input swagger.yaml --output app --generate-routers --specify-tags \"Wild Boars, Fat Cats\"\n```\n\n\n<details>\n<summary>swagger.yaml</summary>\n<pre>\n<code>\nopenapi: \"3.0.0\"\ninfo:\n  version: 1.0.0\n  title: Swagger Petstore\n  license:\n    name: MIT\nservers:\n  - url: /\n  - url: http://petstore.swagger.io/v1\n  - url: http://localhost:8080/\npaths:\n  /boars:\n    get:\n      summary: List All Wild Boars\n      operationId: listWildBoars\n      tags:\n        - Wild Boars\n      parameters:\n        - name: limit\n          in: query\n          description: How many items to return at one time (max 100)\n          required: false\n          schema:\n            type: integer\n      responses:\n        '200':\n          description: An array of wild boars\n          content:\n            application/json:\n              schema:\n                $ref: \"#/components/schemas/WildBoars\"\n    post:\n      summary: Create a Wild Boar\n      operationId: createWildBoars\n      tags:\n        - Wild Boars\n      responses:\n        '201':\n          description: Null response\n  /boars/{boarId}:\n    get:\n      summary: Info For a Specific Boar\n      operationId: showBoarById\n      tags:\n        - Wild Boars\n      parameters:\n        - name: boarId\n          in: path\n          required: true\n          description: The id of the boar to retrieve\n          schema:\n            type: string\n      responses:\n        '200':\n          description: Expected response to a valid request\n          content:\n            application/json:\n              schema:\n                $ref: \"#/components/schemas/Pet\"\n  /cats:\n    get:\n      summary: List All Fat Cats\n      operationId: listFatCats\n      tags:\n        - Fat Cats\n      parameters:\n        - name: limit\n          in: query\n          description: How many items to return at one time (max 100)\n          required: false\n          schema:\n            type: integer\n      responses:\n        '200':\n          description: An array of fat cats\n          content:\n            application/json:\n              schema:\n                $ref: \"#/components/schemas/FatCats\"\n    post:\n      summary: Create a Fat Cat\n      operationId: createFatCats\n      tags:\n        - Fat Cats\n      responses:\n        '201':\n          description: Null response\n  /cats/{catId}:\n    get:\n      summary: Info For a Specific Cat\n      operationId: showCatById\n      tags:\n        - Fat Cats\n      parameters:\n        - name: catId\n          in: path\n          required: true\n          description: The id of the cat to retrieve\n          schema:\n            type: string\n      responses:\n        '200':\n          description: Expected response to a valid request\n          content:\n            application/json:\n              schema:\n                $ref: \"#/components/schemas/Pet\"\n  /dogs:\n    get:\n      summary: List All Slim Dogs\n      operationId: listSlimDogs\n      tags:\n        - Slim Dogs\n      parameters:\n        - name: limit\n          in: query\n          description: How many items to return at one time (max 100)\n          required: false\n          schema:\n            type: integer\n      responses:\n        '200':\n          description: An array of slim dogs\n          content:\n            application/json:\n              schema:\n                $ref: \"#/components/schemas/SlimDogs\"\n    post:\n      summary: Create a Slim Dog\n      operationId: createSlimDogs\n      tags:\n        - Slim Dogs\n      responses:\n        '201':\n          description: Null response\n  /dogs/{dogId}:\n    get:\n      summary: Info For a Specific Dog\n      operationId: showDogById\n      tags:\n        - Slim Dogs\n      parameters:\n        - name: dogId\n          in: path\n          required: true\n          description: The id of the dog to retrieve\n          schema:\n            type: string\n      responses:\n        '200':\n          description: Expected response to a valid request\n          content:\n            application/json:\n              schema:\n                $ref: \"#/components/schemas/Pet\"\ncomponents:\n  schemas:\n    Pet:\n      required:\n        - id\n        - name\n      properties:\n        id:\n          type: integer\n        name:\n          type: string\n        tag:\n          type: string\n    FatCats:\n      type: array\n      description: list of fat cats\n      items:\n        $ref: \"#/components/schemas/Pet\"\n    SlimDogs:\n      type: array\n      description: list of slim dogs\n      items:\n        $ref: \"#/components/schemas/Pet\"\n    WildBoars:\n      type: array\n      description: list of wild boars\n      items:\n        $ref: \"#/components/schemas/Pet\"\n</code>\n</pre>\n</details>\n\n`app/main.py`:\n\n```python\n# generated by fastapi-codegen:\n#   filename:  swagger.yaml\n#   timestamp: 2023-04-04T12:06:16+00:00\n\nfrom __future__ import annotations\n\nfrom fastapi import FastAPI\n\nfrom .routers import fat_cats, slim_dogs, wild_boars\n\napp = FastAPI(\n    version='1.0.0',\n    title='Swagger Petstore',\n    license={'name': 'MIT'},\n    servers=[\n        {'url': '/'},\n        {'url': 'http://petstore.swagger.io/v1'},\n        {'url': 'http://localhost:8080/'},\n    ],\n)\n\napp.include_router(fat_cats.router)\napp.include_router(slim_dogs.router)\napp.include_router(wild_boars.router)\n\n\n@app.get(\"/\")\nasync def root():\n    return {\"message\": \"Gateway of the App\"}\n```\n\n`app/models.py`:\n\n```python\n# generated by fastapi-codegen:\n#   filename:  swagger.yaml\n#   timestamp: 2023-04-04T12:06:16+00:00\n\nfrom __future__ import annotations\n\nfrom typing import List, Optional\n\nfrom pydantic import BaseModel, Field\n\n\nclass Pet(BaseModel):\n    id: int\n    name: str\n    tag: Optional[str] = None\n\n\nclass FatCats(BaseModel):\n    __root__: List[Pet] = Field(..., description='list of fat cats')\n\n\nclass SlimDogs(BaseModel):\n    __root__: List[Pet] = Field(..., description='list of slim dogs')\n\n\nclass WildBoars(BaseModel):\n    __root__: List[Pet] = Field(..., description='list of wild boars')\n```\n\n`app/routers/fat_cats.py`:\n\n```python\n# generated by fastapi-codegen:\n#   filename:  swagger.yaml\n#   timestamp: 2023-04-04T12:06:16+00:00\n\nfrom __future__ import annotations\n\nfrom fastapi import APIRouter\n\nfrom ..dependencies import *\n\nrouter = APIRouter(tags=['Fat Cats'])\n\n\n@router.get('/cats', response_model=FatCats, tags=['Fat Cats'])\ndef list_fat_cats(limit: Optional[int] = None) -> FatCats:\n    \"\"\"\n    List All Fat Cats\n    \"\"\"\n    pass\n\n\n@router.post('/cats', response_model=None, tags=['Fat Cats'])\ndef create_fat_cats() -> None:\n    \"\"\"\n    Create a Fat Cat\n    \"\"\"\n    pass\n\n\n@router.get('/cats/{cat_id}', response_model=Pet, tags=['Fat Cats'])\ndef show_cat_by_id(cat_id: str = Path(..., alias='catId')) -> Pet:\n    \"\"\"\n    Info For a Specific Cat\n    \"\"\"\n    pass\n```\n\n`app/routers/slim_dogs.py`:\n\n```python\n# generated by fastapi-codegen:\n#   filename:  swagger.yaml\n#   timestamp: 2023-04-04T12:06:16+00:00\n\nfrom __future__ import annotations\n\nfrom fastapi import APIRouter\n\nfrom ..dependencies import *\n\nrouter = APIRouter(tags=['Slim Dogs'])\n\n\n@router.get('/dogs', response_model=SlimDogs, tags=['Slim Dogs'])\ndef list_slim_dogs(limit: Optional[int] = None) -> SlimDogs:\n    \"\"\"\n    List All Slim Dogs\n    \"\"\"\n    pass\n\n\n@router.post('/dogs', response_model=None, tags=['Slim Dogs'])\ndef create_slim_dogs() -> None:\n    \"\"\"\n    Create a Slim Dog\n    \"\"\"\n    pass\n\n\n@router.get('/dogs/{dog_id}', response_model=Pet, tags=['Slim Dogs'])\ndef show_dog_by_id(dog_id: str = Path(..., alias='dogId')) -> Pet:\n    \"\"\"\n    Info For a Specific Dog\n    \"\"\"\n    pass\n```\n\n`app/routers/wild_boars.py`:\n\n```python\n# generated by fastapi-codegen:\n#   filename:  swagger.yaml\n#   timestamp: 2023-04-04T12:06:16+00:00\n\nfrom __future__ import annotations\n\nfrom fastapi import APIRouter\n\nfrom ..dependencies import *\n\nrouter = APIRouter(tags=['Wild Boars'])\n\n\n@router.get('/boars', response_model=WildBoars, tags=['Wild Boars'])\ndef list_wild_boars(limit: Optional[int] = None) -> WildBoars:\n    \"\"\"\n    List All Wild Boars\n    \"\"\"\n    pass\n\n\n@router.post('/boars', response_model=None, tags=['Wild Boars'])\ndef create_wild_boars() -> None:\n    \"\"\"\n    Create a Wild Boar\n    \"\"\"\n    pass\n\n\n@router.get('/boars/{boar_id}', response_model=Pet, tags=['Wild Boars'])\ndef show_boar_by_id(boar_id: str = Path(..., alias='boarId')) -> Pet:\n    \"\"\"\n    Info For a Specific Boar\n    \"\"\"\n    pass\n```\n\n`app/dependencies.py`:\n\n```python\n# generated by fastapi-codegen:\n#   filename:  swagger.yaml\n#   timestamp: 2023-04-04T12:06:16+00:00\n\nfrom __future__ import annotations\n\nfrom typing import Optional\n\nfrom fastapi import Path\n\nfrom .models import FatCats, Pet, SlimDogs, WildBoars\n```\n## PyPi \n\n[https://pypi.org/project/fastapi-code-generator](https://pypi.org/project/fastapi-code-generator)\n\n## License\n\nfastapi-code-generator is released under the MIT License. http://www.opensource.org/licenses/mit-license\n\n\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": null,
    "version": "0.5.1",
    "project_urls": {
        "Homepage": "https://github.com/koxudaxi/fastapi-code-generator",
        "Repository": "https://github.com/koxudaxi/fastapi-code-generator"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "b62c093e40e0c97a2e9e575b77341b373d4f2e53708adfaa051ecf375e88000b",
                "md5": "0bbf922c717a0a18577867ae8e04ce0e",
                "sha256": "c1f5c055a73716eebb008c72be93ab6cc8114d643eeb2bd74b3303903055084b"
            },
            "downloads": -1,
            "filename": "fastapi_code_generator-0.5.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "0bbf922c717a0a18577867ae8e04ce0e",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0.0,>=3.8.0",
            "size": 18633,
            "upload_time": "2024-07-02T14:26:26",
            "upload_time_iso_8601": "2024-07-02T14:26:26.209899Z",
            "url": "https://files.pythonhosted.org/packages/b6/2c/093e40e0c97a2e9e575b77341b373d4f2e53708adfaa051ecf375e88000b/fastapi_code_generator-0.5.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "ad2d2bddf102e4d48cf7b56e246bf1a51672abe18b922a326522d119a866df6d",
                "md5": "9b3f604710739c4b71f971a6d3e8dc11",
                "sha256": "ab1f507ec85db1af3f3e3638f8f70872e52ad8bf494697a75bd0580f49766e29"
            },
            "downloads": -1,
            "filename": "fastapi_code_generator-0.5.1.tar.gz",
            "has_sig": false,
            "md5_digest": "9b3f604710739c4b71f971a6d3e8dc11",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0.0,>=3.8.0",
            "size": 18911,
            "upload_time": "2024-07-02T14:26:28",
            "upload_time_iso_8601": "2024-07-02T14:26:28.049421Z",
            "url": "https://files.pythonhosted.org/packages/ad/2d/2bddf102e4d48cf7b56e246bf1a51672abe18b922a326522d119a866df6d/fastapi_code_generator-0.5.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-07-02 14:26:28",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "koxudaxi",
    "github_project": "fastapi-code-generator",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "fastapi-code-generator"
}
        
Elapsed time: 0.30689s