Explain Codes LogoExplain Codes Logo

Return HTTP status code 201 in flask

python
http-status-codes
flask-api
response-formatting
Anton ShumikhinbyAnton Shumikhin·Mar 5, 2025
TLDR

HTTP status code 201 represents successful resource creation in a REST API. To return this code in Flask, you can simply append it to the response tuple:

from flask import Flask, jsonify @app = Flask(__name__) @app.route('/create', methods=['POST']) def create_resource(): # Somewhere over here, a wonderful resource is born 👶 return jsonify({'message': 'It’s alive! Resource created 🎉'}), 201

This ensures your API communicates clearly that a new resource was indeed created successfully.

Returning Non-JSON Responses

Flask supports responses in various formats, not solely JSON. If HTML content is the order of the day, check the snippet below:

from flask import Flask, render_template @app = Flask(__name__) @app.route('/create', methods=['POST']) def create_html_resource(): # Using Hollywood star for the rendering 🎬 response = render_template('created.html'), 201 return response, {'ContentType':'text/html'}

This tasty serving of code returns a 201 status code with HTML content, with MIME type of text/html to ensure the client knows just what they're getting.

Custom Headers and Standard Status Code Use

Custom headers can easily ride along your response, especially when you want to impart additional info. The format of your response statement would be:

# Note the stowaway - the headers 👜 return data, status_code, headers

Keep in mind, to follow the HTTP protocol standards, your status codes should be integers. Adhere to standard conventions, ensuring you convey the right message with the right status code.

Explicitly creating exceptions? Not necessary here.

ANSI certified "success status" 201 does not require custom exceptions. Exceptions usually crash the party when you're dealing with error response codes (4xx, 5xx). Let's keep them at bay for successes, shall we?

Including JSON Data in the Response

Adding JSON data to your 201 response can reveal much valuable information about the newborn resource:

# Additional Nostradamus-like prophecies about the resource 🔮 return jsonify({'id': new_resource_id, 'message': 'Check this out! Resource created.'}), 201

Provision of this extra data as part id or a URL can provide even smoother client experiences.

Squaring Up Your Response

To ensure proper formatting of your responses:

  1. Implement testing to validate response structure.
  2. Use decorators or middlewares for central response formatting.

Ensuring standardised response structures helps in maintaining a consistent conversation with your server's clients.

Handling Errors

The abort function brings everything to a standstill with an error status, should something go awry before the new resource sees the light of the day. It's not a party tool for 201 celebrations!