Day 13 of the Anvil Advent Calendar

Build a web app every day until Christmas, with nothing but Python!

Add to your Wish List by Command Line

Earlier this month, we built an app for creating a Christmas wishlist. We’ve extended the app to allow the owner to add items and to view the wishlist by email. But what about those of you who don’t want to deal with email clients, or even use any GUI at all? Well, now you can add to your Christmas list using the good old command line.

To do this, you just need to pass a JSON body containing the description of your desired item and, optionally, a photo url. The call also requires the email and password you used to sign up to the app, in order to authenticate you.

curl -H 'Content-Type: application/json' -d '{"description": "Item description", "photo": "photo URL' -X POST https://[APP URL] -u email:password

Find our example version of the app here:

Just make sure to be a well-behaved command line user, or you might end up on Santa’s Naughty List!

How it works

Similarly to last time, the first step in adding this functionality was to create a new server function. This time, we added the @anvil.server.http_endpoint("/AddGift") decorator, which sets up this function to be called when that API endpoint is hit. We also added the parameter methods=[‘POST’] to that decorator, as this is a POST only endpoint. The final parameter, authenticate_users=True, means that Anvil will handle authentication for us, by making sure only registered users can access this endpoint.

We then parse the JSON, using the anvil.URLMedia() function to convert the JSON payload into a media object, and add the resulting item to the wishlist. If all goes well, the method returns a success message!

@anvil.server.http_endpoint("/AddGift", methods=['POST'], authenticate_users=True)
def newgift_http():
  item = {"description": anvil.server.request.body_json['description']}
  if 'photo' in  anvil.server.request.body_json:
  return f"Your item has been added"

To see how this app was built in more detail or to play around with it, follow the link below to clone it!

Give the Gift of Python

Share this post: