Python – Make an HTTP request and use the returned JSON

In Python the requests module makes it simple to make HTTP requests and handle the returned JSON.

I have a web API that returns exchange rates for a given currency. In this article, I’ll show how to use the requests module to call this endpoint and use the returned JSON. This will include error handling, just like you would do in production code.

Note: I am using Python 3.

1 – Install the requests module

You can use pip to install the requests module. Execute the following from the command line:

pip install requests
Code language: Python (python)

If everything went well, it should say it successfully installed. At the time of this writing, the current version of requests is 2.25.0.

Installing collected packages: requests Successfully installed requests-2.25.0
Code language: plaintext (plaintext)

2 – Make the HTTP request

I have a local web API running on http://127.0.0.1:12345. This returns exchange rates for the given currency.

To make the HTTP GET request, use requests.get() like this:

import requests try: response = requests.get(f'http://127.0.0.1:12345/currencyexchange/exchangerates', {'currency':'USD'}) response.raise_for_status() except requests.RequestException as reqEx: print(reqEx)
Code language: Python (python)

This makes an HTTP GET request to the specified endpoint and passes in the “currency” query string parameter. It returns the HTTP response, including the content (which we’ll get to next).

HTTP Request Error Handling

It’s always a good idea to handle errors properly from the very beginning.

Notice two things about the code:

  • It’s being executed in a try/except block that handles requests.RequestException.
  • It’s calling response.raise_for_status(), which throws an exception if the HTTP status code isn’t 200.

requests.RequestException is a general-purpose exception that encapsulates all exceptions that the requests module can raise. If you want to handle specific types of exceptions differently, then add an except block for each type. The main types of specific exceptions are: requests.ConnectionError, requests.HTTPError, and requests.Timeout.

3 – Use the returned JSON

To get the JSON content from the HTTP response object, call response.json(). This converts the JSON content to a dictionary object.

Note: If it can’t parse the JSON content, it’ll raise a ValueError exception, so be sure to handle this exception.

import requests import pprint try: response = requests.get(f'http://127.0.0.1:12345/currencyexchange/exchangerates', {'currency':'USD'}) response.raise_for_status() #Converts response.content JSON into a dictionary object currencyExchangeRates = response.json() pprint.pprint(currencyExchangeRates) #Query the dictionary object for a key print(f"The USD:Indian Rupee exchange rate is: {currencyExchangeRates['exchangeRates']['Indian Rupee']}") except ValueError as ve: print("Invalid JSON returned") except requests.RequestException as reqEx: print(reqEx)
Code language: Python (python)

Running this outputs the following:

{'currencyName': 'USD', 'exchangeRates': {'British Pound': 0.749285, 'Chinese Renminbi': 6.576036, 'Euro': 0.841045, 'Indian Rupee': 73.915515, 'Mexican Peso': 20.090097}} The USD:Indian Rupee exchange rate is: 73.915515
Code language: plaintext (plaintext)

Note: The pprint module pretty prints objects. When you pretty print dictionaries, it looks like pretty-printed JSON, as shown above.

Leave a Comment