I have a web application which is backed by REST API located on the same server. Let's say I have a Task
resource accessible on /api/task/<task_id>
and a web page /create-task
which is basically just a form to create a task. There are several ways how to do it:
a) Communicate with REST API using Javascript (don't want to do that)
b) Create object directly in a database
@app.route('/create-task', methods=['POST'])
def create_task(self):
# create an object
try:
task = Task(request.form)
except:
# handle errors and put them to form
pass
# save it into db
task.save()
c) call REST API using requests
library
@app.route('/create-task', methods=['POST'])
def create_task(self):
# send request to REST API
r = requests.post(url_for('api.task', _external=True), json=request.form.data)
if r.status_code != 200:
# handle errors and put them to form
pass
What option would you consider to be the best practice? Think of issues associated with error handling and forms.
Bonus question concerning flask-restful
. Let's say I have already a working API built with flask-restful and want to use option b). Can I somehow use TaskResource.post
to do that?