Skip to main content

No project description provided

Project description

fastapi-code-generator

This code generator creates FastAPI app from an openapi file.

PyPI version Downloads PyPI - Python Version codecov license Code style: black

This project is an experimental phase.

fastapi-code-generator uses datamodel-code-generator to generate pydantic models

Help

See documentation for more details.

Installation

To install fastapi-code-generator:

$ 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
  --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.

Example

OpenAPI

$ fastapi-codegen --input api.yaml --output app
api.yaml

```yaml
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
      items:
        $ref: "#/components/schemas/Pet"
    Error:
      required:
        - code
        - message
      properties:
        code:
          type: integer
          format: int32
        message:
          type: string
```

app/main.py:

# 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

from .models import Pet, Pets

app = FastAPI()


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


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


@app.get('/pets/{pet_id}', response_model=Pet)
def show_pet_by_id(pet_id: str) -> Pet:
    pass

app/models.py:

# generated by datamodel-codegen:
#   filename:  api.yaml
#   timestamp: 2020-06-14T10:45:22+00:00

from typing import List, Optional

from pydantic import BaseModel


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


class Pets(BaseModel):
    __root__: List[Pet]


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

Custom Template

If you want to generate custom *.py files then you can give custom template directory fastapi-code-generator as -t or --template-dir options of the command.

fastapi-code-generator search jinja2 template files in given template directory.

These files will be rendered and write to the output directory. Also, the generated file name will be created template file name which extension is replace to *.py.

Variables

You can use below variables in jinja2 template

  • 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

default template

main.jinja2

from __future__ import annotations

from fastapi import FastAPI

{{imports}}

app = FastAPI()


{% 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}}:
    pass
{% endfor %}

PyPi

https://pypi.org/project/fastapi-code-generator

License

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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastapi-code-generator-0.0.14.tar.gz (12.1 kB view details)

Uploaded Source

Built Distribution

fastapi_code_generator-0.0.14-py3-none-any.whl (10.1 kB view details)

Uploaded Python 3

File details

Details for the file fastapi-code-generator-0.0.14.tar.gz.

File metadata

  • Download URL: fastapi-code-generator-0.0.14.tar.gz
  • Upload date:
  • Size: 12.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.6.1 requests/2.24.0 setuptools/50.3.2 requests-toolbelt/0.9.1 tqdm/4.51.0 CPython/3.8.6

File hashes

Hashes for fastapi-code-generator-0.0.14.tar.gz
Algorithm Hash digest
SHA256 0574924849dc585fd996896f91c9665492df5409fc65fc89d778ad593e11ca2c
MD5 2b704e46885903eec43263ccf4a47d3d
BLAKE2b-256 21174f2f6309519985c0da4bc0c049ef2a0603ca3c600f497f4b132c26fe8dc1

See more details on using hashes here.

File details

Details for the file fastapi_code_generator-0.0.14-py3-none-any.whl.

File metadata

  • Download URL: fastapi_code_generator-0.0.14-py3-none-any.whl
  • Upload date:
  • Size: 10.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.6.1 requests/2.24.0 setuptools/50.3.2 requests-toolbelt/0.9.1 tqdm/4.51.0 CPython/3.8.6

File hashes

Hashes for fastapi_code_generator-0.0.14-py3-none-any.whl
Algorithm Hash digest
SHA256 98781fdee3dc111e3950be938c161f69d36480a4176dcfe58647941a95fb802d
MD5 b379210964ddab8bb0b7626ca439b6f4
BLAKE2b-256 17048005cfb40f393f5c44fd612d28dca9de0bb7fb50a9cdb3b96267c9f26289

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page