👽️ How to consume an API with Python¶
To consume an API in a simple way with python we will use the library called requests.
🔧 Preparing the Environment¶
⌨️ Code¶
In this example we are going to consume an API that will return random fun facts and print it on screen.
consume_api.py | |
---|---|
- Importing the requests library
- Performing the get on endpoint
/fun/facts
in the API - Checking if the request returned any error status_code, in case of error it will generate an exception of type
HTTPError
(Line 9 handle this) - Convert response to json and get first element from the return list
- Print on screen the random fun fact
- If line 6 raise an
HTTPError
exception, here it will be handled - Print status_code information and the error