0

I want to build a web service in python using flask library but I got stuck at the beginning. I managed to succeed with Get methods but I am having some trouble with my POST method. The problem I am having is that when I send a Json data with the POST method my program crashes with the following error: "ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

During handling of the above exception, another exception occurred:" If I send the request without the data everything works fine.

Below is the code for the method POST from the server. I kept it basic so I could find the error easier.

class End_Point(Resource):
    def POST(self):
        return 1

api.add_resource(End_Point,'/end_point')

Here is how I make the request that crashes my program:

url = 'http://127.0.0.1:5000/end_point'
response = requests.post(url, data=json.dumps("123"), headers=headers)

Do you have any idea what am I doing wrong?

Alastair McCormack
  • 26,573
  • 8
  • 77
  • 100

1 Answers1

2

You need to send it as an object/dictionary so you can actually access the value by a name on the server.

server:

from flask import Flask, request
from flask_restful import Resource, Api, reqparse

app = Flask(__name__)
api = Api(app)

parser = reqparse.RequestParser()
parser.add_argument('mynum', type=int, help='mynum is a number')

class EndPoint(Resource):

  def post(self):
    args = parser.parse_args()
    return {"status": "ok", "mynum": args['mynum']}

api.add_resource(EndPoint, '/end_point')

if __name__ == '__main__':
    app.run(debug=True)

client:

import requests
import json

headers = {'content-type': 'application/json'}
url = 'http://localhost:5000/end_point'
response = requests.post(url, data=json.dumps(dict(mynum=123)), headers=headers)
print('response', response.text)
Jack
  • 20,735
  • 11
  • 48
  • 48
  • I still get the same error. Can it be that i have a mistake somewhere else in the code? I forgot to post my headers: "headers = {'content-type': 'application/json'}" – Pantiru Gabriel Mar 03 '17 at 08:42
  • Damn it! Yours is working :)) I will get right on it to see whats wrong. Thanks a lot and have a good day :D – Pantiru Gabriel Mar 03 '17 at 09:20