Reputation: 33
I'm setting up an API REST with flask-restful. I have not found any documentation nor examples of how an internal call among endpoints would be done. Said otherway, I want to consume one of the endpoints from inside the implementation of other endpoint.
I could treat it like an usual external call to another API but I feel like I would be commiting a crime against good practices somehow
from flask import Flask, request
from flask_restplus import Api, Resource
app = Flask(__name__)
api = Api(app, version='1.0', title='FooTitle',
description='FooDescription', )
ns_conf = api.namespace('FooName', description='FooDescription')
# Endpoint 1
@ns_conf.route('/endpoint1')
class MyResource(Resource):
def get(self):
return 'Hello '
# Endpoint 2
@ns_conf.route('/endpoint2')
@api.doc(params={'your_name': 'Your name'})
class greeting(Resource):
def get(self):
# Transfer request parameters to variables:
your_name= request.args.get('your_name')
# I WOULD LIKE TO GET THE OUTPUT OF ENDPOINT 1 here:
hello = call_endpoint_1()
return hello + str(your_name)
What is the correct way to implement 'call_endpoint_1()'?
Upvotes: 2
Views: 1915
Reputation: 77902
Quite simply: factor out the common part into a plain function and call it from both endpoints:
def say_hello():
return "Hello "
@ns_conf.route('/endpoint1')
class MyResource(Resource):
def get(self):
return say_hello()
# Endpoint 2
@ns_conf.route('/endpoint2')
@api.doc(params={'your_name': 'Your name'})
class greeting(Resource):
def get(self):
# Transfer request parameters to variables:
your_name= request.args.get('your_name')
# I WOULD LIKE TO GET THE OUTPUT OF ENDPOINT 1 here:
hello = say_hello()
return hello + str(your_name)
Upvotes: 1