Call an API from PyScript

TL, DR

PyScript is a new and cool piece of technology that let you use Python in the browser. In this tutorial we will call an API from PyScript and display the result on our webpage. More tutorials on PyScript to come!

How to make HTTP requests from PyScript to an external API?

Call an API from PyScript
A webpage with PyScript fetching cat facts from an open API.

PyScript, a cool piece of technology supported by the Anaconda team, embeds Python straight into your browser without any server needed.

In order to get the most out of it, you may want to integrate your PyScript webpage with an external API. You may want to make GET calls. Or POST something from people visiting your webpage to a certain endpoint. But PyScript does not support the famous Python Requests package.

The browser is mostly suitable for running async code, and Requests is a sync package. So you’d better find an alternative solution.

Luckily you can use the pyfetch module from Pyodide, which is a wrapper around the JavaScript fetch package. But there are a couple of points where you need to pay attention to the async nature of this module. Let’s see how it works!

Making your async API call

With only a few lines of code we can create a webpage with PyScript making a request to retrieve a fun cat fact from an open API, and display it on the webpage. Let’s see the overall picture:

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
        <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
        <style>
            h1 {
                text-align: center;
                font-family: Arial, Helvetica, sans-serif;
                font-size: 40px;
            }
        </style>
    </head>
    <body>
        <h1>PyScript - HTTP Requests pyfetch</h1>
        <div>
            <p>
                This webpage fetches a cat fact from <a href="https://alexwohlbruck.github.io/cat-facts/", target="_blank">cat-facts</a> and displays below request status and response text.
            </p>
            <p>
                It uses pyfetch wrapper from pyodide in order to have an async request. Remember to import asyncio and await for the response...we are in asyincland in the browser!
            </p>
            <p>
                Overall, I believe Pyscript is very cool! :-)
            </p>
        </div>
        <div id="request_status"></div>
        <div id="request_text"></div>

    <py-script>
from pyodide.http import pyfetch
import asyncio

response = await pyfetch(url="https://cat-fact.herokuapp.com/facts/random", method="GET")
response_dict = await response.json()

status = f"Request status: {response.status}"
text = f"Text: {response_dict['text']}"

pyscript.write('request_status', status)
pyscript.write('request_text', text)

    </py-script>
    </body>
</html>

There are a few steps that require some further explanation. Those lines in the head section source the PyScript code (yes, it’s a JavaScript file) and its style sheet.

<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>

In the first part of our PyScript code (contained within the <pyscript> tags) we import the packages we need to make an API call:

from pyodide.http import pyfetch
import asyncio

You note the await needed when making a call to the API endpoint and parsing the response:

response = await pyfetch(url="https://cat-fact.herokuapp.com/facts/random", method="GET")
response_dict = await response.json()

Finally, we use the pyscript.write() function to write content inside some named HTML element in our webpage. The id of the element needs to match the first parameter in the pyscript.write() function. The second parameter is what we need to write inside that element.

pyscript.write('request_status', status)
pyscript.write('request_text', text)

That’s it, now you can make GET, POST, or any other HTTP request using PyScript in your webpage! I will publish further tutorials on PyScript, you can find them at this link (also reported below).

Related links

  • More posts about PyScript link
  • PyScript homepage link
  • Pyodide homepage link
  • Blog posts from John Hanley about PyScript link
  • Blog post about HTTP requests in PyScript link
  • GitHub repo with PyScript examples link

Do you like our content? Check more of our posts in our blog!