I am making an API with Flask and Flask-RESTful. When I went to a url in my browser to make a HTTP GET request I got a strange warning in the chromium developer console:
Resource interpreted as Document but transferred with MIME type application/json: "http://localhost:8080/api/articles".
So I looked it up and this article suggested that I changed the mime type to text/html
which didn't work.
Also when I tested this out with my front-end angular didn't automatically turn it into json, what it normally does.
So why does this happen?
I noticed one strange thing. A normal view with jsonify
that returned the same thing as the flask restfull resource did work. So I thought I try to do add the jsonify
to the return and it works.
My question is why does this only work when I use the jsonify
function and otherwise not. In the docs of Flask-RESTful
it says it doesn't need the jsonify
function. Because the @api.representation('application/json')
uses json.dumps
and adds mime type on every outgoing response.
class ArticleList(Resource):
def get(self):
results = models.Article.query.all()
return [x.as_dict() for x in results] # doesn't work
# return jsonify([x.as_dict() for x in results]) this does work
I also did GET request with curl with the jsonify
and without.
With jsonify
panter@panter:~$ curl -X GET http://localhost:8080/api/articles -v
Note: Unnecessary use of -X or --request, GET is already inferred.
* Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /api/articles HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.47.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: application/json
< Content-Length: 560
< Date: Sat, 15 Apr 2017 19:46:46 GMT
<
[
{
"body": "boeeeeeem",
"id": 1,
"picture": null,
"timestamp": "za, 15 apr 2017 17:56:48",
"title": "Vandaag in nuenen een grote explosie!"
}
]
without jsonify
panter@panter:~$ curl -X GET http://localhost:8080/api/articles -v
Note: Unnecessary use of -X or --request, GET is already inferred.
* Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /api/articles HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.47.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: application/json
< Content-Length: 466
< Date: Sat, 15 Apr 2017 19:43:20 GMT
<
[{"body": "boeeeeeem", "picture": null, "id": 1, "timestamp": "za, 15 apr 2017 17:56:48", "title": "Vandaag in nuenen een grote explosie!"}]
Also note that I have changed @api.representation('application/json')
to add some custom headers:
@api.representation('application/json')
def output_json(data, code, headers=None):
resp = make_response(json.dumps(data), code)
all_headers = {
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS, PUT, PATCH, DELETE',
'Access-Control-Allow-Origin': '*'
}.copy()
all_headers.update(headers)
resp.headers.extend(all_headers)
return resp
When using jsonify, these custom headers aren't used.