I have a very simple API. You give it a name, email, address, age, and it returns:
{
'your name is':name,
'your email is': email,
'your address is': address,
'your age is': age
}
However I am trying to make these parameters optional.
So I can call the API with http://127.0.0.1:5000/overflow_test/name=John
i.e. name only. Or I can call with just name and email http://127.0.0.1:5000/overflow_test/name=John&email='email@gmail.com
I believe my problem lies in the api.add_resource
section below:
from flask import Flask
from flask_restful import Resource, Api
import requests
app = Flask(__name__)
api = Api(app)
class hlr_lookup(Resource):
def get(self,name,email,address,age):
return {
'your name is':name,
'your email is': email,
'your address is': address,
'your age is': age
}
api.add_resource(hlr_lookup,'/overflow_test/<string:name><string:email><string:address><string:age>')
if __name__ == '__main__':
app.run(debug=True)
I have tried many different variations of that add_resource
line.
I have checked related questions here, but the answers all structure the request like this: '/overflow_test/parameter1/parameter2/parameter3/paramter4'
i.e. all the parameters are separated by a slash /
.
Is it possible to do it separated by ampersands? &
? It's the style of API I'm more used to using.
http://127.0.0.1:5000/overflow_test/name=John&email='email@gmail.com
The current output if I just use the name John
:
# api call
http://127.0.0.1:5000/overflow_test/name=John
# result
{
"your name is": "name=J",
"your email is": "o",
"your address is": "h",
"your age is": "n"
}
Solved by using flask-resful's reqparse.
More info here: https://blog.miguelgrinberg.com/post/designing-a-restful-api-using-flask-restful
from flask import Flask
from flask_restful import Resource, Api
from flask_restful import reqparse
app = Flask(__name__)
api = Api(app)
class print_stuff(Resource):
def __init__(self):
self.reqparse = reqparse.RequestParser()
self.reqparse.add_argument('name', type = str, default='')
self.reqparse.add_argument('email', type = str, default='')
self.reqparse.add_argument('address', type = str, default='')
self.reqparse.add_argument('age', type = str, default='')
super(hlr_lookup, self).__init__()
def get(self):
args = self.reqparse.parse_args()
return {
'your name is':args['name'],
'your email is': args['email'],
'your address is': args['address'],
'your age is': args['age']
}
api.add_resource(print_stuff,'/overflow_test')
if __name__ == '__main__':
app.run(debug=True)
Now I can call the api like this:
127.0.0.1:5000/print_stuff?name=John&age=23&address=main street new york&email=something@gmail.com