All Projects → koxudaxi → Fastapi Code Generator

koxudaxi / Fastapi Code Generator

Licence: mit
This code generator creates FastAPI app from an openapi file.

Programming Languages

python
139335 projects - #7 most used programming language

Projects that are alternatives of or similar to Fastapi Code Generator

Openapi Mock Generator
Progressive Web App for generating mocked data from an OpenAPI specification
Stars: ✭ 72 (-52%)
Mutual labels:  openapi, generator
Api Generator
PHP-code generator for Laravel framework, with complete support of JSON-API data format
Stars: ✭ 244 (+62.67%)
Mutual labels:  openapi, generator
Generators
API Generator - instantly generate REST and GraphQL APIs (openapi (OAS) 3.0.0)
Stars: ✭ 213 (+42%)
Mutual labels:  openapi, generator
Openapi Typescript Codegen
NodeJS library that generates Typescript or Javascript clients based on the OpenAPI specification
Stars: ✭ 249 (+66%)
Mutual labels:  openapi, generator
Datamodel Code Generator
Pydantic model generator for easy conversion of JSON, OpenAPI, JSON Schema, and YAML data sources.
Stars: ✭ 393 (+162%)
Mutual labels:  openapi, generator
Swaggen
OpenAPI/Swagger 3.0 Parser and Swift code generator
Stars: ✭ 385 (+156.67%)
Mutual labels:  openapi, generator
modelina
Library for generating data models based on inputs such as AsyncAPI, OpenAPI, or JSON Schema documents.
Stars: ✭ 55 (-63.33%)
Mutual labels:  generator, openapi
Openapi Generator
OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)
Stars: ✭ 10,634 (+6989.33%)
Mutual labels:  openapi, generator
Openapi Python Client
Generate modern Python clients from OpenAPI
Stars: ✭ 126 (-16%)
Mutual labels:  openapi, generator
Gf Cli
GoFrame Command Line Interface, which is your helpmate for building GoFrame application with convenience.
Stars: ✭ 143 (-4.67%)
Mutual labels:  generator
Jhipster Dotnetcore
JHipster.NET blueprint
Stars: ✭ 144 (-4%)
Mutual labels:  generator
Puppet Retrospec
The only tool you need to generate puppet code, tests, modules, facts, types, providers, data and everything else.
Stars: ✭ 141 (-6%)
Mutual labels:  generator
Tropical Fish
Pragmatic 风格的 Java EE 后端开发脚手架,开箱即用。基于 SpringBoot,技术选型采用主流的框架(Mybatis-Plus,Redisson,Xxl-job,Swagger)。项目特点:自定义查询语法, 可以自由组装查询条件查询数据,配合代码生成模块,提高研发效率;自定义 service 方法级别的文档生成规则,在业务方法增加必要的注解,可生成方法调用树,快速把握复杂代码业务逻辑。
Stars: ✭ 142 (-5.33%)
Mutual labels:  generator
Json2builtvalue
Json to Dart built_value classes generator
Stars: ✭ 145 (-3.33%)
Mutual labels:  generator
Gh Actions Yaml Generator
Ghygen is a GitHub Actions configurator for your Laravel Application.
Stars: ✭ 142 (-5.33%)
Mutual labels:  generator
Vanity Eth
⚡ Browser-based ETH vanity address generator
Stars: ✭ 148 (-1.33%)
Mutual labels:  generator
Project Webcube
Continuously updated JS infrastructure for modern web dev
Stars: ✭ 141 (-6%)
Mutual labels:  generator
Gofakeit
Random fake data generator written in go
Stars: ✭ 2,193 (+1362%)
Mutual labels:  generator
Generator Standard Readme
Scaffold out a Standard Readme
Stars: ✭ 150 (+0%)
Mutual labels:  generator
Og Image
Open Graph Image as a Service - generate cards for Twitter, Facebook, Slack, etc
Stars: ✭ 2,706 (+1704%)
Mutual labels:  generator

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

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

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, 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:

# 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 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
    • operation.summary a summary

default template

main.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 %}

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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].