diff --git a/docs/tutorials/index.md b/docs/tutorials/index.md index fb89b72a..457fab3e 100644 --- a/docs/tutorials/index.md +++ b/docs/tutorials/index.md @@ -20,6 +20,7 @@ glob: --- writing-to-page py-click +requests ``` ## PyScript Configuration diff --git a/docs/tutorials/requests.md b/docs/tutorials/requests.md new file mode 100644 index 00000000..e0c2aa9d --- /dev/null +++ b/docs/tutorials/requests.md @@ -0,0 +1,123 @@ +# Calling an API using Requests + +This tutorial will show you how to interact with an API using the [Requests](https://requests.readthedocs.io/en/master/) library. Requests is a popular library, but it doesn't work out of the box with Pyscript. We will use the [pyodide-http](https://github.com/koenvo/pyodide-http) library to patch the Requests library, so it works with Pyscript. + + We will use the [JSON Placeholder API](https://jsonplaceholder.typicode.com/), a free fake API that returns fake data. + +## Development Setup + +Let's build the base HTML page to add our `py-config` and `py-script` tags in the next steps. + +```html + + + + + + + Requests Tutorial + + + + + + + +``` + +## Installing the dependencies + +In this step, we will install the dependencies we need to use the Requests library. We will use the `py-config` tag to specify the dependencies we need to install. + +```html + + + + + + + Requests Tutorial + + + + + + + packages = ["requests", "pyodide-http"] + + + +``` + +## Patching the Requests library + +Now that we have installed the dependencies, we need to patch the Requests library to work with Pyscript. We will use the `py-script` tag to specify the code that will be executed when the page is loaded. + +```html + + + + + + + Requests Tutorial + + + + + + + packages = ["requests", "pyodide-http"] + + + + import pyodide_http + pyodide_http.patch() + + + + + + + + + Requests Tutorial + + + + + + + packages = ["requests", "pyodide-http"] + + + + import requests + import pyodide_http + + # Patch the Requests library so it works with Pyscript + pyodide_http.patch() + + # Make a request to the JSON Placeholder API + response = requests.get("https://jsonplaceholder.typicode.com/todos") + print(response.json()) + + + +``` + +## Conclusion + +In this tutorial, we learned how to use the Requests library to make requests to an API. We also learned how to use the `py-config` and `py-script` tags to install dependencies and execute code when the page is loaded. + +Depending on the API you use, you may need to add additional headers to your request. You can read the [Requests documentation](https://requests.readthedocs.io/en/master/user/quickstart/#custom-headers) to learn more about how to do this. + +You may also be interested in creating your module to make requests. You can read the in-depth guide on [How to make HTTP requests using `PyScript`, in pure Python](../guides/http-requests.md) to learn more about how to do this.