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.
pyscript:main
← emirkmo:requests_alternative_demo
opened 02:45PM - 03 May 22 UTC
### Summary
Add a basic asynchronus demo in pure python for using `pyodide.http… .pyfetch` for making HTTP requests.
### Description
`pyfetch` is the `pyodide` alternative for pythons widely used `requests` module (or other modules like httpx/urllib), since they are currently not supported in `pyodide`.
This demo uses the `pyodide` wrapper around javascript `fetch()`, called `pyfetch` to make "GET, POST, PUT, DELETE" requests to show how it can be done. Basically allows interfacing with a REST API from `pyscript`.
It's a simple modification of the Hello World demo to make a few requests to the free https://jsonplaceholder.typicode.com API.
### Reason
See several issues and posts on anaconda forum asking about the same question.
Users are suprised that requests doesn't work and there are no existing simple python demos to show how it works.
Especially for making POST requests with a body and headers, etc.
Note: demo requires python>=3.10.
### Related issues:
#91 #111
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?