response.json() - Python requests - GeeksforGeeks (2024)

Last Updated : 06 Mar, 2024

Summarize

Comments

Improve

Python requests are generally used to fetch the content from a particular resource URL. Whenever we make a request to a specified URL through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.json() out of a response object. It is one of the most used methods in the requests module.

How to use response.json() using Python requests?

response.json() is a part of the requests module in Python so, firstly we have to install the requests module in Python. response.json() is widely used to fetch data from APIs. In this article, we will explore how to use response.json() to load JSON data into Python objects.

Parsing Python requests Response JSON Content

In the below code, firstly we imported the requests module and then fetch the data from an API using requests.get() method and store in variable ‘response’. When we print the response it prints ‘<Response [200]>’ which is the HTTP code that indicates success. To print the JSON data fetched we have used json() method which prints the JSON data in the Python dictionary format as seen in the output. In this way, we can pas parse JSON responses in Python.

Python3

# import requests module

import requests

# Making a get request

response = requests.get('https://api.github.com')

# print response

print(response)

# print json content

print(response.json())

Output:

response.json() - Python requests - GeeksforGeeks (1)

Convert Request Response to Dictionary in Python

In the below code, we will parse the JSON data and print that data same as we access the keys and values of a dictionary. After making the get request to an API we store the JSON data in a variable “API_Data” using the response.json() method. Then we iterate over the JSON data using for loop and print the data by using the keys.

Python3

# import requests module

import requests

# Making a get request

response = requests.get('https://api.github.com')

# Store JSON data in API_Data

API_Data = response.json()

# Print json data using loop

for key in API_Data:{

print(key,":", API_Data[key])

}

Output:

response.json() - Python requests - GeeksforGeeks (2)How to Pretty Print a JSON Object From Python Requests

In the below code, we will pretty print the JSON object that we got from an API using request.get() method. For that after converting the JSON object to the dictionary and stored into “response_dict” we will apply the json.dumps() method on data stored in “response_dict”. We will apply indentation on data by passing the argument “indent=4” and sorting the keys by setting “sort_keys=True” and then printing the data. We can see in the output that data is sorted in increasing order and with indentation.

Python3

# import required modules

import requests

import json

# Making a get request

response = requests.get('https://api.github.com')

# Convert json into dictionary

response_dict = response.json()

# Pretty Printing JSON string back

print(json.dumps(response_dict, indent=4, sort_keys=True))

Output:

response.json() - Python requests - GeeksforGeeks (3)

Advanced Concepts:

There are many libraries to make an HTTP request in Python, which are httplib, urllib, httplib2, treq, etc., but requests are one of the best with cool features. If any attribute of requests shows NULL, check the status code using the below attribute.

requests.status_code

If status_code doesn’t lie in the range of 200-29. You probably need to check the method begin used for making a request + the URL you are requesting for resources.



Please Login to comment...

response.json() - Python requests - GeeksforGeeks (2024)
Top Articles
Real Estate Investors and Taxes | Goodegg Investments
American Eagle Gold Proof Coin | U.S. Mint
Mickey Moniak Walk Up Song
Automated refuse, recycling for most residences; schedule announced | Lehigh Valley Press
Food King El Paso Ads
Devon Lannigan Obituary
Txtvrfy Sheridan Wy
Seething Storm 5E
Craigslist Mexico Cancun
Mndot Road Closures
Espn Expert Picks Week 2
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Declan Mining Co Coupon
Luciipurrrr_
How To Delete Bravodate Account
Yesteryear Autos Slang
Thotsbook Com
Charmeck Arrest Inquiry
Vanessa West Tripod Jeffrey Dahmer
Costco Gas Foster City
TBM 910 | Turboprop Aircraft - DAHER TBM 960, TBM 910
Metro Pcs.near Me
Katie Sigmond Hot Pics
Dallas Mavericks 110-120 Golden State Warriors: Thompson leads Warriors to Finals, summary score, stats, highlights | Game 5 Western Conference Finals
Craigslist Lake Charles
Www Pointclickcare Cna Login
Roanoke Skipthegames Com
Tuw Academic Calendar
Skepticalpickle Leak
How To Improve Your Pilates C-Curve
The Monitor Recent Obituaries: All Of The Monitor's Recent Obituaries
Guide to Cost-Benefit Analysis of Investment Projects Economic appraisal tool for Cohesion Policy 2014-2020
Mosley Lane Candles
Sam's Club Gas Price Hilliard
What are the 7 Types of Communication with Examples
Gridwords Factoring 1 Answers Pdf
Soiza Grass
Cars And Trucks Facebook
Ducky Mcshweeney's Reviews
Linabelfiore Of
Vanessa West Tripod Jeffrey Dahmer
Telugu Moviez Wap Org
Google Flights Orlando
Japanese Big Natural Boobs
Rhode Island High School Sports News & Headlines| Providence Journal
Ig Weekend Dow
Best Restaurants West Bend
Autum Catholic Store
Academic Calendar / Academics / Home
Mybiglots Net Associates
My Gsu Portal
One Facing Life Maybe Crossword
Latest Posts
Article information

Author: Merrill Bechtelar CPA

Last Updated:

Views: 6321

Rating: 5 / 5 (50 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Merrill Bechtelar CPA

Birthday: 1996-05-19

Address: Apt. 114 873 White Lodge, Libbyfurt, CA 93006

Phone: +5983010455207

Job: Legacy Representative

Hobby: Blacksmithing, Urban exploration, Sudoku, Slacklining, Creative writing, Community, Letterboxing

Introduction: My name is Merrill Bechtelar CPA, I am a clean, agreeable, glorious, magnificent, witty, enchanting, comfortable person who loves writing and wants to share my knowledge and understanding with you.