Skip to content

Instantly share code, notes, and snippets.

@armsp
Created August 26, 2018 09:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save armsp/861dddc6f2188d1e12713aaedbd77bbb to your computer and use it in GitHub Desktop.
Save armsp/861dddc6f2188d1e12713aaedbd77bbb to your computer and use it in GitHub Desktop.
Proper way to return HTTP status codes with custom messages when a restful API on Flask server fails while processing inputs.
from flask import Flask, request, abort
from flask_restful import Api, Resource
app = Flask(__name__)
api = Api(app)
class TestExceptions(Resource):
def get(self):
#input_data = request.get_json(force=True)
input_data = {}
input_data['data'] = "Jon"
try:
print("Okay")
#raise ValueError
except ValueError:
print('Value Error')
else:
print("Try block was successfull")
finally:
print('Prints no matter what.')
if isinstance(input_data['data'], str):
#raise ValueError('You passed a string instead of a number')
abort (400, description='You passed a string instead of a number')
return 'You entered {}.'.format(input_data['data'])
api.add_resource(TestExceptions, '/exceptions')
app.run(host='localhost', port=5000, debug=True)

HTTP Error Codes

  • 1xx : Informational
  • 2xx : Success
  • 3xx : Redirection
  • 4xx : Client Error
  • 5xx : Server Error

HTTP Status Codes from MDN

200 OK

400 Bad Request

HTTP request that was sent to the server has invalid syntax.
E.g:

  • The user's cookie that is associated with the site is corrupt. Clearing the browser's cache and cookies could solve this issue
  • Malformed request due to a faulty browser
  • Malformed request due to human error when manually forming HTTP requests (e.g. using curl incorrectly)

401 Unauthorized

403 Forbidden

404 Not Found

500 Internal Server Error

Server cannot process the request for an unknown reason.

Lets say in your Rest API, the client sent some data that while processing results in some exception, then its most probably a 400 Bad Request HTTP Status code. Basically anything you cannot do but is asked for by the client and you are able to catch it is 400.

In flask use the abort function to return custom/corresponding status codes and message descriptions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment