Web API and render template, should they be in the same function call?
I am new to web development. Now I am implementing a simple form to create / edit a user with a submit button.
I would like to know how best to practice this.
I have already defined this kind of web api
URL Method Description
/users/ GET Gives a list of all users
/users/ POST Creates a new user
/users/<id> GET Shows a single user
/users/<id> PUT Updates a single user
/users/<id> DELETE Deletes a single user
My first approach:
I am creating two new functions "/ user / add" and "/ usr / edit" which is similar to
app.route("/users/edit")
def edit_user(){
....
....
call the internal api /user/ with a "put" method
....
render_template("edit.html")
when i click submit button i call the above internal api / users /, method = PUT, and make the final template.
My second approach:
in my internal api / user /, I am trying to read the http header to see if I want to use html template or json text and return to user
Let's say again when I want to create an edit form, instead of calling / user / edit I call / user / using the PUT method
def put(self, id):
//see the header of that request
if header == html
render_template("edit.html", .....)
if header == json
update the record
#
my question, basically, i don't know if the route "/ user / add" "/ user / edit" is needed to make the form, or we can just insert into / user / api with different "post", or "put" ...
the idea comes from here, from flask , a pluggable view I am wondering how to make a better implementation
Or is this the best way to do it ???
Many thanks.
source to share
I would take your first approach because your urls are clear and logical. Also, you separate your interface (site with forms) and backend (API), which is very useful in testing. A normal web browser only makes GET and POST requests to the website, so it is very difficult to render the template with a PUT request to the user, since the user usually cannot run the post request.
source to share