APIFlask is a lightweight Python web API framework based on Flask. It's easy to use, highly customizable, ORM/ODM-agnostic, and 100% compatible with the Flask ecosystem.
APIFlask supports both marshmallow schemas and Pydantic models through a pluggable schema adapter system, giving you the flexibility to choose the validation approach that best fits your project.
With APIFlask, you will have:
More sugars for view function (@app.input(), @app.output(), @app.get(), @app.post() and more)
fromapiflaskimportAPIFlask,Schema,abortfromapiflask.fieldsimportInteger,Stringfromapiflask.validatorsimportLength,OneOfapp=APIFlask(__name__)pets=[{'id':0,'name':'Kitty','category':'cat'},{'id':1,'name':'Coco','category':'dog'}]classPetIn(Schema):name=String(required=True,validate=Length(0,10))category=String(required=True,validate=OneOf(['dog','cat']))classPetOut(Schema):id=Integer()name=String()category=String()@app.get('/')defsay_hello():# returning a dict or list equals to use jsonify()return{'message':'Hello!'}@app.get('/pets/<int:pet_id>')@app.output(PetOut)defget_pet(pet_id):ifpet_id>len(pets)-1:abort(404)# you can also return an ORM/ODM model class instance directly# APIFlask will serialize the object into JSON formatreturnpets[pet_id]@app.patch('/pets/<int:pet_id>')@app.input(PetIn(partial=True))# -> json_data@app.output(PetOut)defupdate_pet(pet_id,json_data):# the validated and parsed input data will# be injected into the view function as a dictifpet_id>len(pets)-1:abort(404)forattr,valueinjson_data.items():pets[pet_id][attr]=valuereturnpets[pet_id]
You can use Pydantic models for type-hint based validation
fromenumimportEnumfromapiflaskimportAPIFlask,abortfrompydanticimportBaseModel,Fieldapp=APIFlask(__name__)classPetCategory(str,Enum):DOG='dog'CAT='cat'classPetOut(BaseModel):id:intname:strcategory:PetCategoryclassPetIn(BaseModel):name:str=Field(min_length=1,max_length=50)category:PetCategorypets=[{'id':0,'name':'Kitty','category':'cat'},{'id':1,'name':'Coco','category':'dog'}]@app.get('/')defsay_hello():return{'message':'Hello, Pydantic!'}@app.get('/pets')@app.output(list[PetOut])defget_pets():returnpets@app.get('/pets/<int:pet_id>')@app.output(PetOut)defget_pet(pet_id:int):ifpet_id>len(pets)orpet_id<1:abort(404)returnpets[pet_id-1]@app.post('/pets')@app.input(PetIn,location='json')@app.output(PetOut,status_code=201)defcreate_pet(json_data:PetIn):# the validated and parsed input data will# be injected into the view function as a Pydantic model instancenew_id=len(pets)+1new_pet=PetOut(id=new_id,name=json_data.name,category=json_data.category)pets.append(new_pet)returnnew_pet
In a word, to make Web API development in Flask more easily, APIFlask provides APIFlask and APIBlueprint to extend Flask's Flask and Blueprint objects and it also ships with some helpful utilities. Other than that, you are actually using Flask.