New python-fastapi generator (#9611)

* [python-fastapi] Added new generator

See https://fastapi.tiangolo.com/ for more details about FastAPI

Signed-off-by: Nikita Vakula <programmistov.programmist@gmail.com>

* [python-fastapi] Added samples

Signed-off-by: Nikita Vakula <programmistov.programmist@gmail.com>
This commit is contained in:
Nikita Vakula
2021-05-30 11:43:31 +02:00
committed by GitHub
parent dee2840b20
commit 0da4099868
52 changed files with 3483 additions and 0 deletions

View File

@@ -0,0 +1,189 @@
# coding: utf-8
from typing import Dict, List
from fastapi import (
APIRouter,
Body,
Cookie,
Depends,
Form,
Header,
Path,
Query,
Response,
Security,
status,
)
from openapi_server.models.extra_models import TokenModel
from openapi_server.models.api_response import ApiResponse
from openapi_server.models.pet import Pet
from openapi_server.security_api import get_token_petstore_auth, get_token_api_key
router = APIRouter()
@router.post(
"/pet",
responses={
200: {"model": Pet, "description": "successful operation"},
405: {"description": "Invalid input"},
},
tags=["pet"],
summary="Add a new pet to the store",
)
async def add_pet(
pet: Pet = Body(None, description="Pet object that needs to be added to the store")
,
token_petstore_auth: TokenModel = Security(
get_token_petstore_auth, scopes=["write:pets", "read:pets"]
),
) -> Pet: # noqa: E501
...
@router.delete(
"/pet/{petId}",
responses={
400: {"description": "Invalid pet value"},
},
tags=["pet"],
summary="Deletes a pet",
)
async def delete_pet(
petId: int = Path(None, description="Pet id to delete")
,
api_key: str = Header(None, description="")
,
token_petstore_auth: TokenModel = Security(
get_token_petstore_auth, scopes=["write:pets", "read:pets"]
),
) -> None: # noqa: E501
...
@router.get(
"/pet/findByStatus",
responses={
200: {"model": List[Pet], "description": "successful operation"},
400: {"description": "Invalid status value"},
},
tags=["pet"],
summary="Finds Pets by status",
)
async def find_pets_by_status(
status: List[str] = Query(None, description="Status values that need to be considered for filter")
,
token_petstore_auth: TokenModel = Security(
get_token_petstore_auth, scopes=["read:pets"]
),
) -> List[Pet]: # noqa: E501
"""Multiple status values can be provided with comma separated strings"""
...
@router.get(
"/pet/findByTags",
responses={
200: {"model": List[Pet], "description": "successful operation"},
400: {"description": "Invalid tag value"},
},
tags=["pet"],
summary="Finds Pets by tags",
)
async def find_pets_by_tags(
tags: List[str] = Query(None, description="Tags to filter by")
,
token_petstore_auth: TokenModel = Security(
get_token_petstore_auth, scopes=["read:pets"]
),
) -> List[Pet]: # noqa: E501
"""Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing."""
...
@router.get(
"/pet/{petId}",
responses={
200: {"model": Pet, "description": "successful operation"},
400: {"description": "Invalid ID supplied"},
404: {"description": "Pet not found"},
},
tags=["pet"],
summary="Find pet by ID",
)
async def get_pet_by_id(
petId: int = Path(None, description="ID of pet to return")
,
token_api_key: TokenModel = Security(
get_token_api_key
),
) -> Pet: # noqa: E501
"""Returns a single pet"""
...
@router.put(
"/pet",
responses={
200: {"model": Pet, "description": "successful operation"},
400: {"description": "Invalid ID supplied"},
404: {"description": "Pet not found"},
405: {"description": "Validation exception"},
},
tags=["pet"],
summary="Update an existing pet",
)
async def update_pet(
pet: Pet = Body(None, description="Pet object that needs to be added to the store")
,
token_petstore_auth: TokenModel = Security(
get_token_petstore_auth, scopes=["write:pets", "read:pets"]
),
) -> Pet: # noqa: E501
...
@router.post(
"/pet/{petId}",
responses={
405: {"description": "Invalid input"},
},
tags=["pet"],
summary="Updates a pet in the store with form data",
)
async def update_pet_with_form(
petId: int = Path(None, description="ID of pet that needs to be updated")
,
name: str = Form(None, description="Updated name of the pet")
,
status: str = Form(None, description="Updated status of the pet")
,
token_petstore_auth: TokenModel = Security(
get_token_petstore_auth, scopes=["write:pets", "read:pets"]
),
) -> None: # noqa: E501
...
@router.post(
"/pet/{petId}/uploadImage",
responses={
200: {"model": ApiResponse, "description": "successful operation"},
},
tags=["pet"],
summary="uploads an image",
)
async def upload_file(
petId: int = Path(None, description="ID of pet to update")
,
additional_metadata: str = Form(None, description="Additional data to pass to server")
,
file: str = Form(None, description="file to upload")
,
token_petstore_auth: TokenModel = Security(
get_token_petstore_auth, scopes=["write:pets", "read:pets"]
),
) -> ApiResponse: # noqa: E501
...

View File

@@ -0,0 +1,91 @@
# coding: utf-8
from typing import Dict, List
from fastapi import (
APIRouter,
Body,
Cookie,
Depends,
Form,
Header,
Path,
Query,
Response,
Security,
status,
)
from openapi_server.models.extra_models import TokenModel
from openapi_server.models.order import Order
from openapi_server.security_api import get_token_api_key
router = APIRouter()
@router.delete(
"/store/order/{orderId}",
responses={
400: {"description": "Invalid ID supplied"},
404: {"description": "Order not found"},
},
tags=["store"],
summary="Delete purchase order by ID",
)
async def delete_order(
orderId: str = Path(None, description="ID of the order that needs to be deleted")
,
) -> None: # noqa: E501
"""For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors"""
...
@router.get(
"/store/inventory",
responses={
200: {"model": Dict[str, int], "description": "successful operation"},
},
tags=["store"],
summary="Returns pet inventories by status",
)
async def get_inventory(
token_api_key: TokenModel = Security(
get_token_api_key
),
) -> Dict[str, int]: # noqa: E501
"""Returns a map of status codes to quantities"""
...
@router.get(
"/store/order/{orderId}",
responses={
200: {"model": Order, "description": "successful operation"},
400: {"description": "Invalid ID supplied"},
404: {"description": "Order not found"},
},
tags=["store"],
summary="Find purchase order by ID",
)
async def get_order_by_id(
orderId: int = Path(None, description="ID of pet that needs to be fetched")
,
) -> Order: # noqa: E501
"""For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generated exceptions"""
...
@router.post(
"/store/order",
responses={
200: {"model": Order, "description": "successful operation"},
400: {"description": "Invalid Order"},
},
tags=["store"],
summary="Place an order for a pet",
)
async def place_order(
order: Order = Body(None, description="order placed for purchasing the pet")
,
) -> Order: # noqa: E501
...

View File

@@ -0,0 +1,171 @@
# coding: utf-8
from typing import Dict, List
from fastapi import (
APIRouter,
Body,
Cookie,
Depends,
Form,
Header,
Path,
Query,
Response,
Security,
status,
)
from openapi_server.models.extra_models import TokenModel
from openapi_server.models.user import User
from openapi_server.security_api import get_token_api_key
router = APIRouter()
@router.post(
"/user",
responses={
200: {"description": "successful operation"},
},
tags=["user"],
summary="Create user",
)
async def create_user(
user: User = Body(None, description="Created user object")
,
token_api_key: TokenModel = Security(
get_token_api_key
),
) -> None: # noqa: E501
"""This can only be done by the logged in user."""
...
@router.post(
"/user/createWithArray",
responses={
200: {"description": "successful operation"},
},
tags=["user"],
summary="Creates list of users with given input array",
)
async def create_users_with_array_input(
user: List[User] = Body(None, description="List of user object")
,
token_api_key: TokenModel = Security(
get_token_api_key
),
) -> None: # noqa: E501
...
@router.post(
"/user/createWithList",
responses={
200: {"description": "successful operation"},
},
tags=["user"],
summary="Creates list of users with given input array",
)
async def create_users_with_list_input(
user: List[User] = Body(None, description="List of user object")
,
token_api_key: TokenModel = Security(
get_token_api_key
),
) -> None: # noqa: E501
...
@router.delete(
"/user/{username}",
responses={
400: {"description": "Invalid username supplied"},
404: {"description": "User not found"},
},
tags=["user"],
summary="Delete user",
)
async def delete_user(
username: str = Path(None, description="The name that needs to be deleted")
,
token_api_key: TokenModel = Security(
get_token_api_key
),
) -> None: # noqa: E501
"""This can only be done by the logged in user."""
...
@router.get(
"/user/{username}",
responses={
200: {"model": User, "description": "successful operation"},
400: {"description": "Invalid username supplied"},
404: {"description": "User not found"},
},
tags=["user"],
summary="Get user by user name",
)
async def get_user_by_name(
username: str = Path(None, description="The name that needs to be fetched. Use user1 for testing.")
,
) -> User: # noqa: E501
...
@router.get(
"/user/login",
responses={
200: {"model": str, "description": "successful operation"},
400: {"description": "Invalid username/password supplied"},
},
tags=["user"],
summary="Logs user into the system",
)
async def login_user(
username: str = Query(None, description="The user name for login")
,
password: str = Query(None, description="The password for login in clear text")
,
) -> str: # noqa: E501
...
@router.get(
"/user/logout",
responses={
200: {"description": "successful operation"},
},
tags=["user"],
summary="Logs out current logged in user session",
)
async def logout_user(
token_api_key: TokenModel = Security(
get_token_api_key
),
) -> None: # noqa: E501
...
@router.put(
"/user/{username}",
responses={
400: {"description": "Invalid user supplied"},
404: {"description": "User not found"},
},
tags=["user"],
summary="Updated user",
)
async def update_user(
username: str = Path(None, description="name that need to be deleted")
,
user: User = Body(None, description="Updated user object")
,
token_api_key: TokenModel = Security(
get_token_api_key
),
) -> None: # noqa: E501
"""This can only be done by the logged in user."""
...

View File

@@ -0,0 +1,27 @@
# coding: utf-8
"""
OpenAPI Petstore
This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
"""
from fastapi import FastAPI
from openapi_server.apis.pet_api import router as PetApiRouter
from openapi_server.apis.store_api import router as StoreApiRouter
from openapi_server.apis.user_api import router as UserApiRouter
app = FastAPI(
title="OpenAPI Petstore",
description="This is a sample server Petstore server. For this sample, you can use the api key &#x60;special-key&#x60; to test the authorization filters.",
version="1.0.0",
)
app.include_router(PetApiRouter)
app.include_router(StoreApiRouter)
app.include_router(UserApiRouter)

View File

@@ -0,0 +1,24 @@
# coding: utf-8
from datetime import date, datetime
from typing import Dict, List, Optional
from pydantic import BaseModel, EmailStr, validator
class ApiResponse(BaseModel):
"""NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
Do not edit the class manually.
ApiResponse - a model defined in OpenAPI
code: The code of this ApiResponse [Optional].
type: The type of this ApiResponse [Optional].
message: The message of this ApiResponse [Optional].
"""
code: Optional[int] = None
type: Optional[str] = None
message: Optional[str] = None

View File

@@ -0,0 +1,22 @@
# coding: utf-8
from datetime import date, datetime
from typing import Dict, List, Optional
from pydantic import BaseModel, EmailStr, validator
class Category(BaseModel):
"""NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
Do not edit the class manually.
Category - a model defined in OpenAPI
id: The id of this Category [Optional].
name: The name of this Category [Optional].
"""
id: Optional[int] = None
name: Optional[str] = None

View File

@@ -0,0 +1,8 @@
# coding: utf-8
from pydantic import BaseModel
class TokenModel(BaseModel):
"""Defines a token model."""
sub: str

View File

@@ -0,0 +1,30 @@
# coding: utf-8
from datetime import date, datetime
from typing import Dict, List, Optional
from pydantic import BaseModel, EmailStr, validator
class Order(BaseModel):
"""NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
Do not edit the class manually.
Order - a model defined in OpenAPI
id: The id of this Order [Optional].
pet_id: The pet_id of this Order [Optional].
quantity: The quantity of this Order [Optional].
ship_date: The ship_date of this Order [Optional].
status: The status of this Order [Optional].
complete: The complete of this Order [Optional].
"""
id: Optional[int] = None
pet_id: Optional[int] = None
quantity: Optional[int] = None
ship_date: Optional[datetime] = None
status: Optional[str] = None
complete: Optional[bool] = None

View File

@@ -0,0 +1,32 @@
# coding: utf-8
from datetime import date, datetime
from typing import Dict, List, Optional
from pydantic import BaseModel, EmailStr, validator
from openapi_server.models.category import Category
from openapi_server.models.tag import Tag
class Pet(BaseModel):
"""NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
Do not edit the class manually.
Pet - a model defined in OpenAPI
id: The id of this Pet [Optional].
category: The category of this Pet [Optional].
name: The name of this Pet.
photo_urls: The photo_urls of this Pet.
tags: The tags of this Pet [Optional].
status: The status of this Pet [Optional].
"""
id: Optional[int] = None
category: Optional[Category] = None
name: str
photo_urls: List[str]
tags: Optional[List[Tag]] = None
status: Optional[str] = None

View File

@@ -0,0 +1,22 @@
# coding: utf-8
from datetime import date, datetime
from typing import Dict, List, Optional
from pydantic import BaseModel, EmailStr, validator
class Tag(BaseModel):
"""NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
Do not edit the class manually.
Tag - a model defined in OpenAPI
id: The id of this Tag [Optional].
name: The name of this Tag [Optional].
"""
id: Optional[int] = None
name: Optional[str] = None

View File

@@ -0,0 +1,34 @@
# coding: utf-8
from datetime import date, datetime
from typing import Dict, List, Optional
from pydantic import BaseModel, EmailStr, validator
class User(BaseModel):
"""NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
Do not edit the class manually.
User - a model defined in OpenAPI
id: The id of this User [Optional].
username: The username of this User [Optional].
first_name: The first_name of this User [Optional].
last_name: The last_name of this User [Optional].
email: The email of this User [Optional].
password: The password of this User [Optional].
phone: The phone of this User [Optional].
user_status: The user_status of this User [Optional].
"""
id: Optional[int] = None
username: Optional[str] = None
first_name: Optional[str] = None
last_name: Optional[str] = None
email: Optional[str] = None
password: Optional[str] = None
phone: Optional[str] = None
user_status: Optional[int] = None

View File

@@ -0,0 +1,83 @@
# coding: utf-8
from typing import List
from fastapi import APIRouter, Depends, Response, Security, status
from fastapi.openapi.models import OAuthFlowImplicit, OAuthFlows
from fastapi.security import (
HTTPAuthorizationCredentials,
HTTPBasic,
HTTPBasicCredentials,
HTTPBearer,
OAuth2,
OAuth2AuthorizationCodeBearer,
OAuth2PasswordBearer,
SecurityScopes,
)
from fastapi.security.api_key import APIKey, APIKeyCookie, APIKeyHeader, APIKeyQuery
from openapi_server.models.extra_models import TokenModel
def get_token_api_key(
token_api_key_header: str = Security(
APIKeyHeader(name="api_key", auto_error=False)
),
) -> TokenModel:
"""
Check and retrieve authentication information from api_key.
:param token_api_key_header API key provided by Authorization[api_key] header
:type token_api_key_header: str
:return: Information attached to provided api_key or None if api_key is invalid or does not allow access to called API
:rtype: TokenModel | None
"""
...
oauth2_implicit = OAuth2(
flows=OAuthFlows(
implicit=OAuthFlowImplicit(
authorizationUrl="http://petstore.swagger.io/api/oauth/dialog",
scopes={
"write:pets": "modify pets in your account",
"read:pets": "read your pets",
}
)
)
)
def get_token_petstore_auth(
security_scopes: SecurityScopes, token: str = Depends(oauth2_implicit)
) -> TokenModel:
"""
Validate and decode token.
:param token Token provided by Authorization header
:type token: str
:return: Decoded token information or None if token is invalid
:rtype: TokenModel | None
"""
...
def validate_scope_petstore_auth(
required_scopes: SecurityScopes, token_scopes: List[str]
) -> bool:
"""
Validate required scopes are included in token scope
:param required_scopes Required scope to access called API
:type required_scopes: List[str]
:param token_scopes Scope present in token
:type token_scopes: List[str]
:return: True if access to called API is allowed
:rtype: bool
"""
return False