Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to customize response content type in flask-restful?

I want to be able to return something other than application/json i.e. kml.

I have the following:

@api.representation('application/vnd.google-earth.kml+xml')
def kml(data):
    return Response(data, mimetype='application/vnd.google-earth.kml+xml')

class mykml(restful.Resource):

    def get(self):
        r = requests.get("http://myurl/kml") # This retrieves a .kml file   
        response = make_response(r.content)
        response.headers['Content-Type'] = "application/vnd.google-earth.kml+xml"

        return response

Why is this still returning application/json? Also, if I have different formats, can I dynamically change the Content-Type of the respone within class mykml without the decorator?

Imports: from flask import Flask, request, Response, session,make_response

like image 550
Rolando Avatar asked Sep 24 '14 18:09

Rolando


People also ask

How do I send a custom response in Flask?

Flask provides a method called make_response() that we can use to send custom headers, as well as change the property (like status_code , mimetype , etc.) in response. We can import make_response from the flask . make_response() accepts a string as a parameter, then creates and returns a response object.

Is Flask GOOD FOR REST API?

However, as it is a newer framework, many more resources and libraries are compatible with frameworks like Django and Flask but not with FastAPI. Being lightweight, easy to adopt, well-documented, and popular, Flask is a good option for developing RESTful APIs.

What is the difference between Flask and Flask RESTful?

Flask Restful is an extension for Flask that adds support for building REST APIs in Python using Flask as the back-end.


1 Answers

If you need a specific response type from an API method, then you'll have to use flask.make_response() to return a 'pre-baked' response object:

def get(self):
    response = flask.make_response(something)
    response.headers['content-type'] = 'application/vnd.google-earth.kml'
    return response
like image 125
Subir Verma Avatar answered Sep 19 '22 01:09

Subir Verma