19 lines
1.4 KiB
Markdown
19 lines
1.4 KiB
Markdown
## Interact with an API with Python
|
|
|
|
I decided to write a simple script to demonstrate this in Python, but it can be done through a REPL as well. In fact, in my current position, I regularly use a Python REPL to introspect and debug APIs in much the same way as I have done in this script. I also use the Linux utility `jq` for this purpose, though its syntax is a bit less readily understandable.
|
|
|
|
I use the `requests` library, even though it's not part of the Python standard library, as it is, in my experience, the de-facto standard for interacting with APIs in Python.
|
|
|
|
The basic code to download 10 random jokes and get just the programming ones is as follows, assuming that the `requests` librarie have been imported:
|
|
|
|
```python
|
|
response = requests.get('https://official-joke-api.appspot.com/jokes/random/10')
|
|
jokes = response.json()
|
|
programming_jokes = [joke for joke in jokes if joke['type'] == 'programming']
|
|
```
|
|
|
|
After this, the `programming_jokes` variable will contain a list of only programming jokes, which can then be further manipulated as I demonstrate in the script.
|
|
|
|
In the script, I filter the programming jokes using a `for` loop rather than list comprehension as I want to avoid duplicates. I do this by storing them in a dictionary rather than a list, indexed on the joke ID. This ensures that, should the API return a duplicate joke, the new version will simply overwrite the old one, and the length of the dictionary will not increase.
|
|
|