Package: webargs-starlette
webargs-starlette is a library for declarative request parsing and
validation withStarlette,
built on top ofwebargs.It has all the goodness ofwebargs,
with some extra sugar for type annotations.importuvicornfromstarlette.applicationsimportStarlettefromstarlette.responsesimportJSONResponsefromwebargs_starletteimportuse_annotationsapp=Starlette()@app.route("/")@use_annotations(location="query")asyncdefindex(request,name:str="World"):returnJSONResponse({"Hello":name})if__name__=="__main__":uvicorn.run(app,port=5000)# curl 'http://localhost:5000/'# {"Hello": "World"}# curl 'http://localhost:5000/?name=Ada'# {"Hello": "Ada"}Installpip install -U webargs-starletteUsageParser UsageUseparser.parseto parse a StarletteRequestwith a
dictionary of fields.fromstarlette.applicationsimportStarlettefromstarlette.responsesimportJSONResponsefromwebargsimportfieldsfromwebargs_starletteimportparserapp=Starlette()@app.route("/")asyncdefhomepage(request):args={"name":fields.Str(required=True),"greeting":fields.Str(load_default="hello"),}parsed=awaitparser.parse(args,request)greeting=parsed["greeting"]name=parsed["name"]returnJSONResponse({"message":f"{greeting}{name}"})DecoratorsUse theuse_argsdecorator to inject the parsed arguments
dictionary into the handler function. The following snippet is equivalent to the
first example.Important: Decorated functions MUST be coroutine functions.fromstarlette.applicationsimportStarlettefromstarlette.responsesimportJSONResponsefromwebargsimportfieldsfromwebargs_starletteimportuse_argsapp=Starlette()@app.route("/")@use_args({"name":fields.Str(required=True),"greeting":fields.Str(load_default="hello")})asyncdefhomepage(request,args):greeting=args["greeting"]name=args["name"]returnJSONResponse({"message":f"{greeting}{name}"})Theuse_kwargsdecorator injects the parsed arguments as keyword arguments.fromstarlette.applicationsimportStarlettefromstarlette.responsesimportJSONResponsefromwebargsimportfieldsfromwebargs_starletteimportuse_argsapp=Starlette()@app.route("/")@use_kwargs({"name":fields.Str(required=True),"greeting":fields.Str(load_default="hello")})asyncdefhomepage(request,name,greeting):returnJSONResponse({"message":f"{greeting}{name}"})Seedecorator_example.pyfor a more complete example ofuse_argsanduse_kwargsusage.Error HandlingWhen validation fails, the parser will raise aWebargsHTTPException,
which is the same as Starlette’sHTTPExceptionwith the addition of
of themessages(validation messages),headers,exception(underlying exception), andschema(marshmallowSchema) attributes.You can use a custom exception handler to return the error messages as
JSON.fromstarlette.responsesimportJSONResponsefromwebargs_starletteimportWebargsHTTPException@app.exception_handler(WebargsHTTPException)asyncdefhttp_exception(request,exc):returnJSONResponse(exc.messages,status_code=exc.status_code,headers=exc.headers)AnnotationsTheuse_annotationsdecorator allows you to parse request objects
using type annotations.fromstarlette.applicationsimportStarlettefromstarlette.responsesimportJSONResponsefromwebargs_starletteimportuse_annotationsapp=Starlette()@app.route("/")@use_annotations(location="query")asyncdefwelcome(request,name:str="Friend"):returnJSONResponse({"message":f"Welcome,{name}!"})# curl 'http://localhost:5000/'.# {"message":"Welcome, Friend!"}# curl 'http://localhost:5000/?name=Ada'.# {"message":"Welcome, Ada!"}Any annotated argument that doesn’t have a default value will be required.
For example, if we remove the default fornamein the above example,
an 422 error response is returned if?nameisn’t passed.fromstarlette.applicationsimportStarlettefromstarlette.responsesimportJSONResponsefromwebargs_starletteimportuse_annotations,WebargsHTTPExceptionapp=Starlette()@app.route("/")@use_annotations(location="query")asyncdefwelcome(request,name:str):returnJSONResponse({"message":f"Welcome,{name}!"})@app.exception_handler(WebargsHTTPException)asyncdefhttp_exception(request,exc):returnJSONResponse(exc.messages,status_code=exc.status_code,headers=exc.headers)# curl "http://localhost:5000/"# {"name":["Missing data for required field."]}Arguments may also be annotated withFieldinstances when you need
more control. For example, you may want to add a validator.fromstarlette.applicationsimportStarlettefromstarlette.responsesimportJSONResponsefromwebargsimportfieldsfrommarshmallowimportvalidatefromwebargs_starletteimportuse_annotations,WebargsHTTPExceptionapp=Starlette()@app.route("/")@use_annotations(location="query")asyncdefwelcome(request,name:fields.Str(validate=validate.Length(min=2))):returnJSONResponse({"message":f"Welcome,{name}!"})@app.exception_handler(WebargsHTTPException)asyncdefhttp_exception(request,exc):returnJSONResponse(exc.messages,status_code=exc.status_code,headers=exc.headers)# curl "http://localhost:5000/?name=A"# {"name":["Shorter than minimum length 2."]}HTTPEndpointmethods may also be decorated withuse_annotations.fromstarlette.applicationsimportStarlettefromstarlette.responsesimportJSONResponsefromstarlette.endpointsimportHTTPEndpointfromwebargs_starletteimportuse_annotationsapp=Starlette()@app.route("/")classWelcomeEndpoint(HTTPEndpoint):@use_annotations(location="query")asyncdefget(self,request,name:str="World"):returnJSONResponse({"message":f"Welcome,{name}!"})Seeannotation_example.pyfor a more complete example ofuse_annotationsusage.MoreFor more information on how to use webargs, see thewebargs documentation.LicenseMIT licensed. See theLICENSEfile for more details.