Docs

Build an HTTP API

An HTTP API is a way for programs to communicate over the internet using HTTP. HTTP is the same protocol used by your web browser, but APIs are built to be used by programs rather than people. py.space makes it easy to build HTTP APIs – let’s see how.

Example: What’s the time?

Did you know that all GPS satellites do is broadcast the current time? Their atomic clocks are so precise that a GPS receiver can receive timestamps from three satellites, measure the tiny differences between them, and work out how far away they are using the speed of light. 🤯

Well, we don’t have an atomic clock, but we can make an API that returns the current time! Here’s an example API that does just that:

Here’s how you build it:

1. Create an HTTP API widget

Go to your account’s homepage, and under “What do you want to build?”, click HTTP API.

By default, the API will come with a little “Hello World” content. Delete that code, and copy-paste the code from the example above.

It contains a function called current_time(), which runs whenever you go to https://your-widget.anvil.app/time. It returns a dictionary, which py.space automatically turns into JSON.

2. Try it out

In the bottom-right of your widget, you’ll see the URL of your function – in our example above, it’s https://bony-spectacular-season.anvil.app/time.

If you’re using Linux or MacOS, you can open a terminal and request that URL with curl. Here’s how that looks for me:

$ curl https://bony-spectacular-season.anvil.app/time
{"time":"2024-05-03T20:46:04.397923"}

Because this is a simple “GET” endpoint, you could also just copy-paste the URL into your browser!

3. See the output

If you look at your widget, you’ll see that your code also print()ed the current time, and that output showed up in the Output panel!

When you’re building an HTTP API, it can get tricky to work out what’s going on when you receive a request. With py.space, it’s easy – you can use print() in your HTTP endpoints, and see your debugging output in the Output panel.

4. Share it!

Click the the Public button at the top of the widget to make it public on your py.space profile!


Do you still have questions?

Our Community Forum is full of helpful information and friendly experts.