Search code examples
pythonpython-3.xflask-restful

Problems while making requests to a flask restful app


I have the following flask api, which just returns echo of its input:

from flask import Flask
from flask_restful import Resource, Api

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

class query(Resource):

    def get(self, a_string):
        return{
        'original': a_string,
        'echo': a_string
        }

api.add_resource(query,'/echo/<a_string>')

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

Then, when I try to use python requests to make queries to my api:

import json
def query(text):    
    payload = {'echo': str(text)}
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    r = requests.request("POST", 'http://127.0.0.1:5000', data=payload, headers=headers)
    print(r)
    #data = json.loads(r.text)
    #return data

query('hi')

I keep getting:

<Response [404]>

Any idea of how to fix this issue? Interestingly when I go to my browser and do:

http://127.0.0.1:5000/echo/hi

I get:

{"original": "hi", "echo": "hi"}

Solution

  • But sending a POST to / with a payload of {"echo": whatever} is not at all the same as sending a GET to /echo/whatever. Your API expects the latter.

    def query(text):
        r = requests.get("http://127.0.0.1:5000/echo/{}".format(text))
    

    Or, change your API so it does expect that:

    class query(Resource):
    
        def post(self):
            a_string = request.form["echo"]
            return {
                'original': a_string,
                'echo': a_string
            }
    
    api.add_resource(query, '/')