Hi all,
I’m going through the blog on “The Easiest Way to Build HTTP or REST APIs in Python”
When I try to add a new task using the POST method I get a method not supported
error.
The server function looks like this:
# Add a new task
@anvil.server.http_endpoint('/new_task', methods=["POST"], authenticate_users=True)
def new_task(**q):
title = anvil.server.request.body_json['title']
new_row = app_tables.tasks.add_row(title=title, done=False,
owner=anvil.users.get_user())
return {'id': new_row.get_id()}
The client call looks like this:
base = anvil.server.call('get_api_origin')
self.new_task_lnk.url = self.new_task_lnk.text = base + "/new_task"
Can anyone explain how to add a task using the POST method here?
Hi @alcampopiano
If you click on a link, your browser makes a GET
request. As you’ve configured your endpoint to be POST
-only, you are correctly getting “Method not supported”!
If you want to invoke an HTTP POST API from code running in the browser in Anvil, you’ll want anvil.http.request()
:
anvil.http.request(base+"/new_task", method="POST")
(In fact, if you make that request from the same Anvil app, your http_endpoint()
will see your current session, and you won’t need to specify a username=
and password=
for the login! If you do your anvil.http.request()
from the server, you’ll need to supply username and password.)
All of this, of course, is rather more complicated than anvil.server.call(...)
…which is why we built it
HTTP endpoints are primarily for communicating with code outside Anvil.
Thanks Meredydd. That clarifies things for me.
Hi @meredydd, data=[…] causes syntax error : bad input, but data={…} doesn’t. Is the system changed recently?
anvil.http.request(url="...", data=[...], json=True, method="POST")