Python program to extract a single value from JSON response (Using API call)
Hello Everyone! In this Python tutorial, we are going to learn how to retrieve Single data or single values from JSON using Python. To perform this task we will be going to use the request module in Python, this module allows users to send HTTP requests and receive responses in form of JSON.
How to extract a single value from JSON response
Let’s start by importing the requests module,
import request import urllib.parse
After importing modules,
import urllib.parse import requests base_url="https://v6.exchangerate-api.com/v6/Enter your API key here/pair/" print("Enter the First Currency") s=input() print("Enter the Second Currency") l=input() value=s+"/"+l url = base_url+value json_data = requests.get(final_url).json() result = json_data['conversion_rate'] print("Conversion rate from "+s+" to "+l+" = ",result)
- Declare base_url with API key variable.
- Take the inputs from the user.
- Add the user input to our base_url and make final_url or make an API request to the server and fetch the data from the server.
- Now, json_data makes an API call and fetches the data from the server & it contains JSON response.
- We will get the result from the website in JSON format.
- So let us create a variable called result which will contain the JSON data and retrieve the single data which is required.
- To retrieve single data like ‘conversion_rate’ you have to declare a variable from the JSON response.
- The ‘result’ variable holds the value of ‘conversion_rate’.
- Final print the result.
JSON RESPONSE
result "success" documentation "https://www.exchangerate-api.com/docs" terms_of_use "https://www.exchangerate-api.com/terms" time_last_update_unix 1615075202 time_last_update_utc "Sun, 07 Mar 2021 00:00:02 +0000" time_next_update_unix 1615161617 time_next_update_utc "Mon, 08 Mar 2021 00:00:17 +0000" base_code "USD" target_code "INR" conversion_rate 73.0648
OUTPUT
Enter the First Currency USD Enter the Second Currency INR Conversion rate from USD to INR = 73.0648
Now, you can understand how to retrieve single data from a variety of other APIs.
Leave a Reply