Generate REST API and OpenAPI documentation for your Flask project.
Flask OpenAPI3 is a web API framework based on Flask. It uses Pydantic to verify data and automatic
generation of interaction documentation: Swagger, ReDoc and RapiDoc.
pyyaml is used to output the OpenAPI document in yaml format.
asgiref allows views to be defined with async def and use await.
To install these dependencies with flask-openapi3:
1 2 3 4 5 6 7 8 91011
pipinstallflask-openapi3[yaml]# or
pipinstallflask-openapi3[async]# or
pipinstallflask-openapi3[dotenv]# or
pipinstallflask-openapi3[email]# or all
pipinstallflask-openapi3[yaml,async,dotenv,email]# or manually
pipinstallpyyamlasgirefpython-dotenvemail-validator
frompydanticimportBaseModelfromflask_openapi3importInfo,Tagfromflask_openapi3importOpenAPIinfo=Info(title="book API",version="1.0.0")app=OpenAPI(__name__,info=info)book_tag=Tag(name="book",description="Some Book")classBookQuery(BaseModel):age:intauthor:str@app.get("/book",summary="get books",tags=[book_tag])defget_book(query:BookQuery):""" to get all books """return{"code":0,"message":"ok","data":[{"bid":1,"age":query.age,"author":query.author},{"bid":2,"age":query.age,"author":query.author}]}if__name__=="__main__":app.run(debug=True)
fromtypingimportOptionalfrompydanticimportBaseModel,Fieldfromflask_openapi3importOpenAPI,Tag,Info,APIViewinfo=Info(title='book API',version='1.0.0')app=OpenAPI(__name__,info=info)api_view=APIView(url_prefix="/api/v1",view_tags=[Tag(name="book")])classBookPath(BaseModel):id:int=Field(...,description="book ID")classBookQuery(BaseModel):age:Optional[int]=Field(None,description='Age')classBookBody(BaseModel):age:Optional[int]=Field(...,ge=2,le=4,description='Age')author:str=Field(None,min_length=2,max_length=4,description='Author')@api_view.route("/book")classBookListAPIView:a=1@api_view.doc(summary="get book list")defget(self,query:BookQuery):print(self.a)returnquery.model_dump_json()@api_view.doc(summary="create book")defpost(self,body:BookBody):"""description for a created book"""returnbody.model_dump_json()@api_view.route("/book/<id>")classBookAPIView:@api_view.doc(summary="get book")defget(self,path:BookPath):print(path)return"get"@api_view.doc(summary="update book")defput(self,path:BookPath):print(path)return"put"@api_view.doc(summary="delete book",deprecated=True)defdelete(self,path:BookPath):print(path)return"delete"app.register_api_view(api_view)if__name__=="__main__":app.run(debug=True)