Computer scienceBackendFlaskLaunching server

Responses

8 minutes read

For every request, there is a response. You can't skip this part as client-server communication implies both sides talking, and responding is just as crucial as processing requests. This topic covers different response types, their features, and how to implement them in Flask.

Getting started with responses

In this topic, we will talk about responses and how our application can send them. Let's start with a simple template for our new app. As always, we need to import it first. Mind the new make_response method:

from flask import Flask
from flask import make_response

app = Flask('main')

In most cases, returning a simple string as a response is insufficient. We'll need a response object, an instance of the Response class. It allows us to set up special properties such as adding headers to an ordinary web page (or rather to the response that returns it), specify the language that is used for the web page, list the allowed methods, like POST, PUT, GET, and many more.

We can create a response object in Flask with the make_response method:

@app.route('/')
def index():
    response = make_response('<h1>The Main Page, OK?</h1>')
    return response

Remember, we are placing the app.route decorator before any function that should handle a page path.

Let's now take a look at what we can do with it:

@app.route('/data/get_error/')
def return_error():
    response = make_response('<p>Oops... Sounds like an error!</p>', 400)
    return response

We route our page to /data/get_error/, so the page can be accessed at 127.0.0.1:5000/data/get_error/.

When routing, always start a URL with a slash.

In this example, we have created a response that contains an HTML template string for a specific page as well as the number 400. The number means the return data with the HTTP status code 400 indicating an error. We can inform users, for example, that at the moment, the page is closed and under construction without knocking down the whole program.

Time to look at our results! First, go to the main page of the app:

main page

Looks pretty good, doesn't it? And now, let's stir the pot and go to /data/get_error/:

/data/get_error/

Holy cats! Who would have thought that this page contains an error? Let's look at the console and make sure that Flask returned this page with the error code:

page contains an error

Jsonify method

Now, we'll switch to another proper method: jsonifyjsonify method helps us to create a proper response object from JSON output. Let's start with the import:

from flask import Flask
from flask import jsonify

app = Flask('main')

Wonderful! Now, onto the central part — the function. We will use jsonify and route it to / to create a response:

@app.route('/')
def no_data():
    response = jsonify({'message': 'Hello there!', 'info': 'Using jsonify...', 'status': 200})

    return response

As you can see, we have a regular dictionary with data. The jsonify method puts it into a JSON object. Jsonify returns a response object, so we don't have to process it with make_response.

After that, we can launch the application with app.run()! Go to 127.0.0.1:5000, and you will see the following:

app.run()

That's how we can send a response with JSON data. In this case, the JSON object will be displayed on the page since we haven't specified how our app should use it. We will get back to this in later topics. Below is the complete code of our app:

from flask import Flask
from flask import jsonify


app = Flask('main')

@app.route('/')
def no_data():
    response = jsonify({'message': 'Hello there!', 'info': 'Using jsonify...', 'status': 200})

    return response

app.run()

Conclusion

We have learned how to create responses from scratch using two methods: make_response() and jsonify. The first handles simple responses, while the second collects data into a JSON object. We are glad that you have reached this point. Carry on!

40 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo