Flask Status Codes
A status code says how a request went. 200 means all went well, and 201 means something was made.
Make the app
This line makes the Flask app. The routes below belong to it.
from flask import Flask
app = Flask(__name__)A route that returns 201
The view returns the text and the code 201 together, as a pair.
@app.route("/created")
def created():
return "Made", 201A route with the default code
This view returns text only, so the status is the default 200.
@app.route("/fine")
def fine():
return "Fine"Ask for the codes
The test client asks for each address and prints the status code it gets back.
client = app.test_client()
print(client.get("/created").status_code)
print(client.get("/fine").status_code)Example
from flask import Flask
app = Flask(__name__)
@app.route("/created")
def created():
return "Made", 201
@app.route("/fine")
def fine():
return "Fine"
client = app.test_client()
print(client.get("/created").status_code)
print(client.get("/fine").status_code)Key points
- A view returns 200 unless it says otherwise.
- Return text with a code, like return "Made", 201.
- 404 means the address does not exist.
- 500 means the app hit an error.
In this example, the /created view returns "Made" with the code 201. The /fine view returns text only, so its code is the default 200. The test client asks for each address and prints the status code.
Note
Status codes are numbers, not text.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
How does a view return the status code 201?