JSON (JavaScript Object Notation) file is a very popular medium to interchange data between different formats. It contains data in text format that is supported by various languages such as Python, PHP, PERL, etc. The main purpose of the JSON file is to transfer data between the server and the client. The requests are generated by Python to retrieve the data from a particular resource URI. If the response of the request is returned in JSON format then the content of the response can be retrieved using the response.json() function. It returns the response by using a Python dictionary object. How this function can be used to parse JSON response using the Python request library will be shown in this tutorial.
JSON Response:
The request module of Python contains the JSON decoder to work with the JSON data. The response.json() function returns a JSON response if the JSON decoder works properly. The response.json() function raises the exception if the JSON decoder fails and the JSON response does not contain any data or invalid data. The return value of the response.raise_for_status() function or the response.status_code is required to be checked before executing the response.json() function.
Different uses of response.json():
Three different uses of the response.json() function will be shown in this part of the tutorial.
Example-1: Simple use of response.json()
The simple use of the response.json() function will be expounded in this example. The response for the get request of the URI, https://api.github.com/ is stored in a variable named response. Next, the value of the response variable is checked. If the response variable contains any invalid response, then it will print an error message. If the response variable contains a valid response which is the status code of the response and its content a success message will print.
import requests
# Create a get request
response = requests.get('https://api.github.com/')
# Check the response
if response:
# Print the response status code
print('The status code of the response is %d' %response.status_code)
# Print the JSON content
print('The JSON content is: \n%s' %response.json())
# Print the success message
print('\nThe request is handled successfully.')
else:
# Print the error message for the invalid response
print('Invalid response.')
Output:
The following output will appear after executing the above script.
Example-2: Use of response.json() with exception handling
The way of using the response.json() function with exception handling will be shown in this example. HttpError module is imported with the request module in the script to handle the exception. Here, the URI address will be taken from the user to use the requests.get() function. The response of this request will be stored in the response variable. Next, response.raise_for_status() function is used to check the response of the request whether it is valid or invalid. If the response is invalid, then an exception will be generated and the code of any except block will be executed based on the exception. If the response is valid, then the content of the response variable will be iterated using a for loop to print the values of the dictionary in each line that contains the response data.
import requests
# Import HTTPError for exception handling
from requests.exceptions import HTTPError
# Define the URI
uri = input('Enter the a valid URI:\n')
# Print waiting message
print('Waiting for the response...\n')
try:
# Create a get request to read feeds content of github
response = requests.get(uri)
# Raise exception if the response was unsuccessful
response.raise_for_status()
# Read the JSON content
jsonResponse = response.json()
print("The JSON content is: \n")
# Read and print each key-value pair from the JSON response
for key, value in jsonResponse.items():
print(key, ":", value)
# Print error message for the HTTP error
except HTTPError as http_err:
print('HTTP error occurred: %s' %http_err)
# Print error message for the HTTP error
except Exception as err:
print('Other error occurred: %s' %err)
Output:
The following output will appear after executing the script when a non-existence URI value will be provided by the user. Here, the HTTPError exception had been generated alongside the corresponding error message.
The following output will appear after executing the script when an invalid URI value will be provided by the user. Here, the other exception had been generated with a corresponding error message.
The following output will appear after executing the script when a valid URI value will be provided by the user. Here, the JSON content has been printed properly.
Example-3: Use of response.json() with query string
The way of using the response.json() function with query string will be shown in this example. Here, the requests.get() function used a query string value with the URI using params. It will search the entries for the PERL language in the given repositories. If the response variable contains a valid response then the repository name and description will be printed, otherwise, there will be an error message.
import requests
# Searching in github's repository using query string
response = requests.get(
'https://api.github.com/search/repositories',
params={'q': 'requests+language:perl'},
)
# Check the response
if response:
# Read the JSON content
json_response = response.json()
# Read the particular repository item
repository = json_response['items'][0]
# Print the repository name
print('Repository name: %s' %repository["name"])
# Print the repository description
print('Repository description: %s' %repository["description"])
else:
# Print the error message for the invalid response
print('Invalid response.')
Output:
The following output will appear after executing the above script. The repository name and description for the PERL language had been printed here.
Conclusion:
Different ways to send the request to a particular URI and read the response using the response.json() function was shown in this tutorial using simple examples. I hope this tutorial will help the readers to understand the use of JSON response in Python and apply it properly in their script when it is required.