Working with APIs
Overview of RESTful APIs in Python
RESTful APIs (Representational State Transfer) is an architectural style that defines a set of constraints to be used for creating web services12. Python provides some great tools not only to get data from REST APIs but also to build your own Python REST APIs1. By using Python and REST APIs, you can retrieve, parse, update, and manipulate the data provided by any web service youâre interested in1.
Example
# Example 1: Importing the requests library
import requests
# Example 2: Defining the API URL
api_url = "https://jsonplaceholder.typicode.com/todos"
# Example 3: Creating a dictionary to send as data
todo = {"userId": 1, "title": "Buy milk", "completed": False}
# Example 4: Sending a POST request
response = requests.post(api_url, json=todo)
# Example 5: Getting the response in JSON format
response_json = response.json()
# Example 6: Getting the status code of the response
status_code = response.status_code
Exercise
Exercise 1: Write a Python function to send a GET request to an API and print the status code of the response.
Answer 1:
def get_request(api_url):
response = requests.get(api_url)
print(response.status_code)
Exercise 2: Write a Python function to send a POST request to an API with a JSON payload and print the response.
Answer 2:
def post_request(api_url, payload):
response = requests.post(api_url, json=payload)
print(response.json())
Exercise 3: Write a Python function to update a resource using a PUT request.
Answer 3:
def put_request(api_url, payload):
response = requests.put(api_url, json=payload)
print(response.json())
Exercise 4: Write a Python function to delete a resource using a DELETE request.
Answer 4:
def delete_request(api_url):
response = requests.delete(api_url)
print(response.status_code)
Exercise 5: Write a Python function to handle exceptions while making API requests.
Answer 5:
def safe_request(api_url, method, payload=None):
try:
if method == 'GET':
response = requests.get(api_url)
elif method == 'POST':
response = requests.post(api_url, json=payload)
elif method == 'PUT':
response = requests.put(api_url, json=payload)
elif method == 'DELETE':
response = requests.delete(api_url)
else:
print("Invalid method")
return
response.raise_for_status()
except requests.exceptions.HTTPError as errh:
print ("HTTP Error:",errh)
except requests.exceptions.ConnectionError as errc:
print ("Error Connecting:",errc)
except requests.exceptions.Timeout as errt:
print ("Timeout Error:",errt)
except requests.exceptions.RequestException as err:
print ("Something went wrong",err)
Making HTTP requests with Python
HTTP requests are a fundamental part of web development and data retrieval. Python provides several libraries to make HTTP requests, with requests
being the most popular due to its simplicity and ease of use1. With the requests
library, you can send HTTP requests using common methods such as GET, POST, PUT, DELETE, etc1.
Example
# Example 1: Importing the requests library
import requests
# Example 2: Making a GET request
response = requests.get('https://jsonplaceholder.typicode.com/posts')
# Example 3: Checking the status code of the response
print(response.status_code)
# Example 4: Printing the content of the response
print(response.text)
# Example 5: Making a POST request
response = requests.post('https://jsonplaceholder.typicode.com/posts', data = {'key':'value'})
# Example 6: Sending a PUT request
response = requests.put('https://jsonplaceholder.typicode.com/posts/1', data = {'key':'value'})
# Example 7: Sending a DELETE request
response = requests.delete('https://jsonplaceholder.typicode.com/posts/1')
Exercise
Exercise 1: Write a Python function to send a GET request to an API and print the status code of the response.
Answer 1:
def get_request(api_url):
response = requests.get(api_url)
print(response.status_code)
Exercise 2: Write a Python function to send a POST request to an API with a JSON payload and print the response.
Answer 2:
def post_request(api_url, payload):
response = requests.post(api_url, json=payload)
print(response.json())
Exercise 3: Write a Python function to update a resource using a PUT request.
Answer 3:
def put_request(api_url, payload):
response = requests.put(api_url, json=payload)
print(response.json())
Exercise 4: Write a Python function to delete a resource using a DELETE request.
Answer 4:
def delete_request(api_url):
response = requests.delete(api_url)
print(response.status_code)
Exercise 5: Write a Python function to handle exceptions while making API requests.
Answer 5:
def safe_request(api_url, method, payload=None):
try:
if method == 'GET':
response = requests.get(api_url)
elif method == 'POST':
response = requests.post(api_url, json=payload)
elif method == 'PUT':
response = requests.put(api_url, json=payload)
elif method == 'DELETE':
response = requests.delete(api_url)
else:
print("Invalid method")
return
response.raise_for_status()
except requests.exceptions.HTTPError as errh:
print ("HTTP Error:",errh)
except requests.exceptions.ConnectionError as errc:
print ("Error Connecting:",errc)
except requests.exceptions.Timeout as errt:
print ("Timeout Error:",errt)
except requests.exceptions.RequestException as err:
print ("Something went wrong",err)
Parsing JSON responses in Python
JSON (JavaScript Object Notation) is a popular data format with diverse uses in data interchange, including that of web services12. Python provides the json
module which can be used to both parse JSON, as well as convert Python objects into JSON3. When dealing with APIs and HTTP responses, the requests
library in Python can be used. It provides a built-in JSON decoder to handle JSON data12.
Example
# Example 1: Importing the necessary libraries
import requests
import json
# Example 2: Making a GET request
response = requests.get('https://api.github.com')
# Example 3: Parsing the JSON response into a Python dictionary
data = response.json()
# Example 4: Accessing elements from the parsed JSON
print(data['current_user_url'])
# Example 5: Pretty printing the parsed JSON
print(json.dumps(data, indent=4))
# Example 6: Handling exceptions while parsing JSON
try:
data = response.json()
except json.JSONDecodeError:
print("Invalid JSON")
except Exception as e:
print(f"Exception occurred: {e}")
Exercise
Exercise 1: Write a Python function to send a GET request to an API and parse the JSON response.
Answer 1:
def get_request(api_url):
response = requests.get(api_url)
data = response.json()
return data
Exercise 2: Write a Python function to pretty print a parsed JSON response.
Answer 2:
def pretty_print_json(data):
print(json.dumps(data, indent=4))
Exercise 3: Write a Python function to access a specific key from a parsed JSON response.
Answer 3:
def access_key(data, key):
return data.get(key)
Exercise 4: Write a Python function to handle exceptions while parsing a JSON response.
Answer 4:
def safe_parse(response):
try:
data = response.json()
except json.JSONDecodeError:
print("Invalid JSON")
data = None
except Exception as e:
print(f"Exception occurred: {e}")
data = None
return data
Exercise 5: Write a Python function to convert a Python dictionary into a JSON string.
Answer 5:
def dict_to_json(data):
json_str = json.dumps(data)
return json_str
Building API clients and wrappers in Python
An API client is any piece of code that consumes an API1. Building API clients and wrappers involves creating a library in your language of choice that helps you abstract away the APIâs implementation details2. You would access the API through calling regular methods provided by the library, rather than constructing HTTP requests from scratch2. These libraries also have the advantage of returning data as familiar data structures provided by the language, hence enabling idiomatic ways to access and manipulate this data2.
Example
# Example 1: Define the API classes
class API1():
def __init__(self, url):
self.url = url
def getData1(self):
return "Getting " + self.url
def postData1(self):
return "Posting " + self.url
class API2():
def __init__(self, url, username):
self.url = url
def getData2(self):
return "Getting " + self.url + " for " + self.username
# Example 2: Define the wrapper class
class wrapped_api():
mapping = {
"getData": {
"API1": "getData1",
"API2": "getData2",
},
"postData": {
"API1": "postData1",
}
}
def __init__(self, api, *args, **kwargs):
instance = api(*args, **kwargs)
for key, val in self.mapping.items():
if api.__name__ in val:
setattr(self, key, getattr(instance, val[api.__name__]))
# Example 3: Use the wrapper class
api1 = wrapped_api(API1, "http://api1.example.com")
api2 = wrapped_api(API2, "http://api2.example.com", "alice")
print(api1.getData())
print(api1.postData())
print(api2.getData())
Exercise
Exercise 1: Write a Python function to send a GET request to an API and print the status code of the response.
Answer 1:
def get_request(api_url):
response = requests.get(api_url)
print(response.status_code)
Exercise 2: Write a Python function to send a POST request to an API with a JSON payload and print the response.
Answer 2:
def post_request(api_url, payload):
response = requests.post(api_url, json=payload)
print(response.json())
Exercise 3: Write a Python function to update a resource using a PUT request.
Answer 3:
def put_request(api_url, payload):
response = requests.put(api_url, json=payload)
print(response.json())
Exercise 4: Write a Python function to delete a resource using a DELETE request.
Answer 4:
def delete_request(api_url):
response = requests.delete(api_url)
print(response.status_code)
Exercise 5: Write a Python function to handle exceptions while making API requests.
Answer 5:
def safe_request(api_url, method, payload=None):
try:
if method == 'GET':
response = requests.get(api_url)
elif method == 'POST':
response = requests.post(api_url, json=payload)
elif method == 'PUT':
response = requests.put(api_url, json=payload)
elif method == 'DELETE':
response = requests.delete(api_url)
else:
print("Invalid method")
return
response.raise_for_status()
except requests.exceptions.HTTPError as errh:
print ("HTTP Error:",errh)
except requests.exceptions.ConnectionError as errc:
print ("Error Connecting:",errc)
except requests.exceptions.Timeout as errt:
print ("Timeout Error:",errt)
except requests.exceptions.RequestException as err:
print ("Something went wrong",err)
Last updated
Was this helpful?