Pyfetch example

Hi All,

I’m looking for an example of calling an external API using pyfetch. If I try this the network call is never made.

from pyodide.http import pyfetch

key = "1232rxnwenwewefWEF@r34d"
endpoint = "https://XXX/"
query = {'blah'}
headers = {'API-Key': key}
response = pyfetch(
    endpoint,
    method="POST",
    body={"query": query},
    headers=headers
)
print(str(response))

Any help appreciated.

pyfetch is an async function, so you need to use await:

response = await pyfetch(...)

You probably will want to actually read the response after that, which requires another await. Furthermore, you should ensure that your endpoint is configured to allow CORS from anywhere.

Here is a PR that adds a simple pyfetch example.

I wanted to see how it works so I played around with it. However, the HTML is very basic, this is just to show how to make pyfetch work.

Thanks @ek2660 PR looks great.

@MARTIN_DURANT you are right about CORS. Not something we needed to consider with Jupyter workflows. Thanks

1 Like

Can we have this inside a function?