Live Chat

We'll need to share your messages (and your email address if you're logged in) with our live chat provider, Drift. Here's their privacy policy.

If you don't want to do this, you can email us instead at contact@anvil.works.

HTTP and REST APIs with Anvil

Are you new here?

Anvil is a tool for building full-stack web apps with nothing but Python and a drag-and-drop designer. Learn more on our website, or sign up and try it yourself -- it's free!

Anvil apps can integrate with external HTTP REST APIs, or expose REST APIs of their own.

Integrating against external REST APIs

(Check out our worked example: Using the GitHub API from Anvil!)

You can integrate against REST APIs using our anvil.http module. To make a GET request, you can run:

resp = anvil.http.request("https://api.mystocks.com/all")

Here’s an example of a POST request:

resp = anvil.http.request(url="https://api.mystocks.com/all",
                    method="POST",
                    data="Data to post",
                    headers= {
                      "Authentication": "my-access-key",
                    })

The resp object is a Python object representing the response. If you use the json=True keyword argument to request, you can access a JSON-formatted response as a Python object

resp = anvil.http.request("https://api.mystocks.com/all", json=True)
print(resp['stocks'])

This works in both client and server code. So you can make HTTP requests from the web browser, subject to the sensible security restrictions placed on HTTP requests by web browsers.

If you want to integrate against Google or Stripe APIs, consider using our Google and Stripe integrations to save time.


Add a REST API to your app

You can create an HTTP endpoint by decorating any function in a Server Module with @anvil.server.http_endpoint and specifying a path:

@anvil.server.http_endpoint("/users/:id")
def get_user(id, **params):
  return {'message':
          "You requested user %s with params %s" % (id, params)}

By default, HTTP endpoints serve their return data as JSON.

You can also integrate HTTP endpoints into Anvil’s Users Service authentication system. This requires users to specify a valid username and password via HTTP Basic authentication:

@anvil.server.http_endpoint("/authenticated_endpoint",
                            authenticate_users=True)
def authenticated_endpoint():
  this_user = anvil.users.get_user()
  return {'username': this_user['email']}

There’s lots more you can do with HTTP endpoints. To learn more, read our documentation on HTTP APIs.