In this Python Flask tutorial, we will learn how to set the content type of our web application. Content type tells the browser about the type of data being sent by the server. Here, we will set the content type to JSON, but it can be set to other types like HTML, XML, etc.
To get started, you will need to have Python and Flask installed on your system. If you don’t have them, you can install them by running the following commands:
pip install Flask
Now, let’s create a simple Flask app that will return a JSON response with a set content type.
-
First, create a new Python file called
app.py
- In the
app.py
file, add the following code:
from flask import Flask, jsonify, Response
app = Flask(__name__)
@app.route('/')
def index():
data = {'message': 'Hello, World!'}
resp = jsonify(data)
resp.headers['Content-Type'] = 'application/json'
return resp
if __name__ == '__main__':
app.run()
In the code above, we import Flask and jsonify from the flask module. We create a Flask app instance and define a route /
that returns a JSON response with the message ‘Hello, World!’. We then set the content type of the response to ‘application/json’.
- To run the Flask app, execute the
app.py
file:
python app.py
- Now, open your web browser and navigate to
http://127.0.0.1:5000/
. You should see a JSON response with the message ‘Hello, World!’ displayed on the page.
That’s it! You have successfully set the content type of your Flask app to JSON. You can also set the content type to other types like HTML, XML, etc., by changing the value of the Content-Type
header in the response.
I hope this tutorial was helpful in understanding how to set the content type in a Python Flask app. Let me know if you have any questions or need further clarification. Thank you for reading!