Package: jsonres
jsonresjsonresis a small, lightweight wrapper around Flask'smake_responseandjsonify, providing a fast and convenient
way to return JSON data with the right HTTP status code.jsonresutilizes HTTP status code messages as methods in a declarative way, you simply call a static method
such asok,not_foundorinternal_server_errorand optionally pass in the data you wish to return as JSON.Python v3.6 +InstallationpipinstalljsonresUsageImport thejsonresonseclassfromjsonresimportjsonresonseYou can now call one of many staticmethods of the classReturn a200 OKstatus code and a dict@app.route("/")defexample():""" Returns a dict with an HTTP 200 OK status code """returnjsonresonse.ok({"message":"ok"})Passing no data to the method returns an empty string@app.route("/")defok():""" Return an empty HTTP 200 OK response """returnjsonresonse.ok()You can optionally pass in a headers dict if required@app.route("/")defexample():""" Return a dict with custom headers """returnjsonresonse.ok(data={"message":"ok"},headers={"X-Custom-Header":"hello!"})Taking a look in the Chrome developer tools, we can see our custom header:Content-Length:17Date:Sun,03May202016:49:41GMT
Content-Type:application/json
Server:Werkzeug/1.0.1Python/3.8.2
X-Custom-Header:hello!jsonreshas methods for all HTTP status codes defined by the ietf -https://tools.ietf.org/html/rfc7231Common status codes include,404 NOT FOUND, here being used in a Flask error handlerdefhandle_not_found_error(e):""" Handler for not found errors """app.logger.warning(e)returnjsonresonse.not_found(data={"message":"Not found"})app.register_error_handler(404,handle_not_found_error)And500 INTERNAL SERVER ERROR@app.route("/internal-server-error")definternal_server_error():msg={"message":"Whoops, we did something wrong"}returnjsonresonse.internal_server_error(msg)Visiting this URL in the browser returns{"message":"Whoops, we did something wrong"}Flask exampleHere's a trivial example, showingjsonresin actionfromflaskimportFlaskfromjsonresimportjsonresonsedefcreate_app():app=Flask(__name__)@app.route("/")defok():""" Return an empty HTTP 200 OK response """returnjsonresonse.ok()@app.route("/dict")defd():""" Return a dict """returnjsonresonse.ok({"message":"ok"})@app.route("/with-headers")defwith_headers():""" Return a dict with custom headers """returnjsonresonse.ok(data={"message":"ok"},headers={"X-Custom-Header":"hello!"})@app.route("/bad-request")defbad_request():""" Return a 400 response with a dict """data={"message":"You did something wrong"}returnjsonresonse.bad_request(data=data)@app.route("/unauthorized")defunauthorized():returnjsonresonse.unauthorized()@app.route("/internal-server-error")definternal_server_error():msg={"message":"Whoops, we did something wrong"}returnjsonresonse.internal_server_error(msg)@app.route("/empty-list")defok_empty_list():""" Return an empty list """returnjsonresonse.ok(data=[])@app.route("/empty-dict")defok_empty_dict():""" Return an empty dict """returnjsonresonse.ok(data={})defhandle_not_found_error(e):""" Handler for not found errors """app.logger.warning(e)returnjsonresonse.not_found(data={"message":"Not found"})defhandle_internal_server_error(e):""" Handler for internal server errors """app.logger.error(e)returnjsonresonse.internal_server_error()app.register_error_handler(404,handle_not_found_error)app.register_error_handler(500,handle_internal_server_error)returnappif__name__=="__main__":app=create_app()app.run()Methods available100 range (informational)methodHTTP Status codecontinue100switching_protocol101processing102early_hints103200 range (success)methodHTTP Status codeok200created201accepted202non_authoritative_information203no_content204reset_content205partial_content206multi_status207already_reported208im_used226300 range (redirection)methodHTTP Status codemultiple_choice300moved_permanently301found302see_other303not_modified304use_proxy305unused306temporary_redirect307permanent_redirect308400 range (client error)methodHTTP Status codebad_request400unauthorized401payment_required402forbidden403not_found404method_not_allowed405not_acceptable406proxy_authentication_required407request_timeout408conflict409gone410length_required411precondition_failed412payload_too_large413uri_too_long414unsupported_media_type415requested_range_not_satisfiable416expectation_failed417im_a_teapot418misdirected_request421unprocessable_entity422locked423failed_dependency424too_early425upgrade_required426precondition_required428too_many_requests429request_header_fields_too_large431unavailable_for_legal_reasons451500 range (server error)methodHTTP Status codeinternal_server_error500not_implemented501bad_gateway502service_unavailable503gateway_timeout504http_version_not_supported505variant_also_negotiates506insufficient_storage507loop_detected508not_extended510network_authentication_required511