I was following this tutorial and it was going pretty well. He then introduced reqparse
and I followed along. I tried to test my code and I get this error
{'message': "Did not attempt to load JSON data because the request Content-Type was not 'application/json'."}
I don't know if I'm missing something super obvious but I'm pretty sure I copied his code exactly. here's the code:
main.py
from flask import Flask, request
from flask_restful import Api, Resource, reqparse
app = Flask(__name__)
api = Api(app)
#basic get and post
names = {"sai": {"age": 19, "gender": "male"},
"bill": {"age": 23, "gender": "male"}}
class HelloWorld(Resource):
def get(self, name, numb):
return names[name]
def post(self):
return {"data": "Posted"}
api.add_resource(HelloWorld, "/helloworld/<string:name>/<int:numb>")
# getting larger data
pictures = {}
class picture(Resource):
def get(self, picture_id):
return pictures[picture_id]
def put(self, picture_id):
print(request.form['likes'])
pass
api.add_resource(picture, "/picture/<int:picture_id>")
# reqparse
video_put_args = reqparse.RequestParser() # make new request parser object to make sure it fits the correct guidelines
video_put_args.add_argument("name", type=str, help="Name of the video")
video_put_args.add_argument("views", type=int, help="Views on the video")
video_put_args.add_argument("likes", type=int, help="Likes on the video")
videos = {}
class Video(Resource):
def get(self, video_id):
return videos[video_id]
def post(self, video_id):
args = video_put_args.parse_args()
print(request.form['likes'])
return {video_id: args}
api.add_resource(Video, "/video/<int:video_id>")
if __name__ == "__main__":
app.run(debug=True)
test_rest.py
import requests
BASE = "http://127.0.0.1:5000/"
response = requests.post(BASE + 'video/1', {"likes": 10})
print(response.json())
I don't know why you have an issue as far as I can tell you did copy him exactly how he did it. Here's a fix that'll work although I can't explain why his code works and yours doesn't. His video is two years old so it could be deprecated behaviour.
import requests
import json
BASE = "http://127.0.0.1:5000/"
payload = {"likes": 10}
headers = {'accept': 'application/json'}
response = requests.post(BASE + 'video/1', json=payload)
print(response.json())