- In this tutorial, we will learn how to fetch JSON data from a URL in Python using the Requests library.
- It involves making an HTTP request to the URL, checking the response status code and parsing the JSON content into a python object using response.json().
- This process allows you to interact with API’s or web applications
Fetch JSON Data from URL in Python Using Requests
Here is a step-by-step explanation:
1.Install the requests Library:
Before using the requests library, ensure it is installed .Use the following command in terminal to install it:
pip install requests
2.Import the requests Library :
Import the requests library at the beginning of your script.
import requests
3.Specify the URL:
Decide on the URL that provides the JSON data to fetch. For example,
url = "https://dog.ceo/api/breeds/image/random"
4.Make a GET Request:
Use the requests.get() method to make an HTTP GET request to the URL. This sends a request to the server and gets a response.
response = requests.get(url)
5.Check the Response Status Code:
Check if the status code indicates success (200). if it is not 200, there may be an issue with the request or server.
if response.status_code == 200: print("request was successful!") else: print(f"Error: Request failed with status code {response.status_code}")
6.Parse the JSON Data:
If the request is successful, use the response.json() method to parse the JSON data from the response into a python dictionary.
data = response.json() print(data)
Complete Code :
import requests #Define URL url = "https://dog.ceo/api/breeds/image/random" #Dog CEO's Dog API URL #Make a GET request to the URL response = request.get(url) # Check if the request was successful if response.status_code == 200: data=response.json() print(data) else: print(f"Error:Request failed with status code {response.status_code}")
Output:
{'message': 'https://images.dog.ceo/breeds/terrier-irish/n02093991_287.jpg', 'status': 'success'}