CHAPTER 9
Working with APIs
Quick intro
Application programming interfaces (APIs) are essential for integrating external data sources and services into your applications.
They allow you to request external servers and receive responses, typically in the form of data you can manipulate and use within your program.
Python provides several libraries to work with APIs, with requests being one of the most popular for making HTTP requests. Additionally, parsing the responses, often in JSON or XML formats, is crucial for utilizing the data effectively.
Note: You can run the following code examples by opening the built-in terminal within VS Code and executing the command: python <script>.py. Replace <script> with the name of the respective Python file to execute.
Making a GET request to a REST API
The requests library simplifies making HTTP requests in Python. It supports various methods, such as GET, POST, PUT, and DELETE, enabling you to interact with RESTful APIs effortlessly.
We’ll start by making a GET request to a public API that provides data about Pokémon.
Code Listing 9-a: getrequest.py
import requests # Define the URL of the API endpoint url = "https://pokeapi.co/api/v2/pokemon/ditto" # Make the GET request response = requests.get(url) # Check if the request was successful if response.status_code == 200: # Parse the JSON response pokemon_data = response.json() print("Name:", pokemon_data['name']) print("Base experience:", pokemon_data['base_experience']) print("Abilities:", [ability['ability']['name'] for ability in pokemon_data['abilities']]) else: print("Failed to retrieve data:", response.status_code) |
Explanation:
· Importing requests:
o import requests imports the requests library to make HTTP requests.
· Defining the URL:
o url = "https://pokeapi.co/api/v2/pokemon/ditto" sets the API endpoint URL for retrieving data about the Pokémon Ditto.
· Making the request:
o response = requests.get(url) sends a GET request to the specified URL and stores the response.
· Checking the response:
o if response.status_code == 200 checks whether the request succeeded (status code 200).
· Parsing JSON data:
o pokemon_data = response.json() parses the JSON response into a Python dictionary.
o print("Name:", pokemon_data['name']) prints the name of the Pokémon.
o print("Base experience:", pokemon_data['base_experience']) prints the base experience value.
o print("Abilities:", [ability['ability']['name']... prints a list of the Pokémon’s abilities.
Parsing and using JSON data
APIs commonly return data in JSON format, which is lightweight and easy to parse in Python using the built-in json module or the requests library’s built-in methods.
Here’s how to parse and manipulate JSON data from an API response.
Code Listing 9-b: parsejson.py
import requests # Define the URL of the API endpoint url = "https://jsonplaceholder.typicode.com/posts/1" # Make the GET request response = requests.get(url) # Check if the request was successful if response.status_code == 200: # Parse the JSON response post_data = response.json() print("Post Title:", post_data['title']) print("Post Body:", post_data['body']) else: print("Failed to retrieve data:", response.status_code) |
Explanation:
· Making the request:
o Similar to the previous code listing example, a GET request is made to the URL https://jsonplaceholder.typicode.com/posts/1, which returns a JSON object representing a post.
· Parsing the response:
o post_data = response.json() converts the JSON response into a Python dictionary.
o print("Post Title:", post_data['title']) and print("Post Body:", post_data['body']) extract and print the title and body of the post.
Making a POST request
POST requests are used to send data to an API. This example demonstrates sending JSON data to a Uniform Resource Identifier (URI) endpoint.
Code Listing 9-c: postrequest.py
import requests # Define the URL of the API endpoint url = "https://jsonplaceholder.typicode.com/posts" # Define the data to be sent in the POST request data = { "title": "foo", "body": "bar", "userId": 1 } # Make the POST request response = requests.post(url, json=data) # Check if the request was successful if response.status_code == 201: # Parse the JSON response post_data = response.json() print("Created Post ID:", post_data['id']) else: print("Failed to create post:", response.status_code) |
Explanation:
· Defining the data: data is a dictionary containing the data sent in the POST request.
· Making the POST request: response = requests.post(url, json=data) sends the data as a JSON payload to the specified URL.
· Checking and parsing the response:
o A successful POST request returns a status code 201.
o The JSON response contains the newly created post, and print("Created Post ID:", post_data['id']) prints the ID of the created post.
Parsing XML responses
Although JSON is more common across APIs and applications, some APIs return XML data. Python’s xml.etree.ElementTree module can parse XML data. Here’s how to parse XML data from an API response.
Code Listing 9-d: parsexml.py
import requests import xml.etree.ElementTree as ET # Define the URL of the API endpoint url = "https://www.w3schools.com/xml/note.xml" # Make the GET request response = requests.get(url) # Check if the request was successful if response.status_code == 200: # Parse the XML response root = ET.fromstring(response.content) print("To:", root.find('to').text) print("From:", root.find('from').text) print("Heading:", root.find('heading').text) print("Body:", root.find('body').text) else: print("Failed to retrieve data:", response.status_code) |
Explanation:
· Importing modules:
o import xml.etree.ElementTree as ET imports the XML parsing module.
· Making the request:
o Similar to previous code snippet examples, a GET request is made to the URL https://www.w3schools.com/xml/note.xml, which returns XML data.
· Parsing the XML response:
o root = ET.fromstring(response.content) parses the XML content into an ElementTree object.
o root.find('to').text extracts the text of the <to> element and similar methods extract other elements.
Recap
By mastering API integration, you can significantly enhance the functionality of your applications, allowing them to interact with external data sources and services.
You can easily make HTTP requests and handle responses using the requests library. Understanding how to parse and manipulate JSON and XML data ensures you can effectively utilize the data returned by APIs.
- 1800+ high-performance UI components.
- Includes popular controls such as Grid, Chart, Scheduler, and more.
- 24x5 unlimited support by developers.