Calling REST API from the same server Calling REST API from the same server flask flask

Calling REST API from the same server


If possible, the actual best thing to do would be to call the API code directly through Python without going through HTTP and REST. This would avoid the overhead and possible failure points of a HTTP request. I'm not familiar with flask-restful so I don't know how easy this might be. The answer in "Calling flask restful API resource methods" seems to suggest just extracting the common code from the API to a library you can use in both the API and your app, which would work too.

Other than that:

A) using Javascript/AJAX might not be too bad if the API doesn't require authentication or isn't meant to be "secret". You'd have to write form error-handling in Javascript but you can avoid the HTTP request to /create-task if the REST API call returns an error.

C) is better than B) because there's less possibility for things breaking. Only the REST API is responsible for creating tasks and all you're doing is passing parameters. The problem is you would need to read out any error responses from the API and re-write them in your form handler, which is dumb work. Also this creates fragility in being able to generate proper URL in url_for('api.task'), being able to access that URL on production servers, and so on.

B) is bad for the same reason copy-pasting code is bad. You now have two places where tasks are created and you have to remember to modify both if changing something (e.g. database implementation details). This will eventually break and come back to hurt you.