Response Methods - Python requests - GeeksforGeeks (2024)

Last Updated : 23 Jul, 2021

Summarize

Comments

Improve

When one makes a request to a URI, it returns a response. This Response object in terms of python is returned by requests.method(), method being – get, post, put, etc. Response is a powerful object with lots of functions and attributes that assist in normalizing data or creating ideal portions of code. For example, response.status_code returns the status code from the headers itself, and one can check if the request was processed successfully or not.
Response object can be used to imply lots of features, methods, and functionalities.
Example :

Python3

# import requests module

import requests

# Making a get request

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

# print request object

print(response.url)

# print status code

print(response.status_code)

Save this file as request.py, and run using below command

Python request.py

Response Methods - Python requests - GeeksforGeeks (1)

Status code 200 indicates that request was made successfully.

Response Methods

MethodDescription
response.headersresponse.headers returns a dictionary of response headers.
response.encodingresponse.encoding returns the encoding used to decode response.content.
response.elapsedresponse.elapsed returns a timedelta object with the time elapsed from sending the request to the arrival of the response.
response.close()response.close() closes the connection to the server.
response.contentresponse.content returns the content of the response, in bytes.
response.cookiesresponse.cookies returns a CookieJar object with the cookies sent back from the server.
response.historyresponse.history returns a list of response objects holding the history of request (url).
response.is_permanent_redirectresponse.is_permanent_redirect returns True if the response is the permanent redirected url, otherwise False.
response.is_redirectresponse.is_redirect returns True if the response was redirected, otherwise False.
response.iter_content()response.iter_content() iterates over the response.content.
response.json()response.json() returns a JSON object of the result (if the result was written in JSON format, if not it raises an error).
response.urlresponse.url returns the URL of the response.
response.textresponse.text returns the content of the response, in unicode.
response.status_coderesponse.status_code returns a number that indicates the status (200 is OK, 404 is Not Found).
response.requestresponse.request returns the request object that requested this response.
response.reasonresponse.reason returns a text corresponding to the status code.
response.raise_for_status()response.raise_for_status() returns an HTTPError object if an error has occurred during the process.
response.okresponse.ok returns True if status_code is less than 200, otherwise False.
response.linksresponse.links returns the header links.

Commonly Used Response Methods

Some methods are most commonly used with response, such as response.json(), response.status_code, response.ok, etc. Requests is mostly used for making http request to APIs(Application Programming Interface). Some of commonly used response methods are discussed here –

response.json()

response.json() returns a JSON object of the result (if the result was written in JSON format, if not it raises an error).

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

To illustrate use of response.json(), let’s ping geeksforgeeks.org. To run this script, you need to have Python and requests installed on your PC.

Example code –

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())

Example Implementation –

Save above file as request.py and run using

Python request.py

Output –

Response Methods - Python requests - GeeksforGeeks (2)

Check the json content at the terminal output. This basically returns a Python dictionary.

response.ok

response.ok returns True if status_code is less than 200, otherwise False.

How to use response.ok using Python requests?

To illustrate use of response.ok, let’s ping geeksforgeeks.org. To run this script, you need to have Python and requests installed on your PC.

Example code –

Python3

# import requests module

import requests

# Making a get request

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

# print response

print(response)

# print if status code is less than 200

print(response.ok)

Example Implementation –

Save above file as request.py and run using

Python request.py

Output –

Response Methods - Python requests - GeeksforGeeks (3)

Check that True which matches the condition of request being less than or equal to 200.

response.status_code

response.status_code returns a number that indicates the status (200 is OK, 404 is Not Found).

How to use response.status_code using Python requests?

To illustrate use of response.status_code, let’s ping api.github.com. To run this script, you need to have Python and requests installed on your PC.

Example code –

Python3

# import requests module

import requests

# Making a get request

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

# print response

print(response)

# print request status_code

print(response.status_code)

Example Implementation –

Save above file as request.py and run using

Python request.py

Output –

Response Methods - Python requests - GeeksforGeeks (4)

Check that and 200 in the output which refer to HttpResponse and Status code respectively.

response.headers

response.headers returns a dictionary of response headers. To check more about headers, visit – Different HTTP Headers

How to use response.headers using Python requests?

To illustrate use of response.headers, let’s ping API of Github. To run this script, you need to have Python and requests installed on your PC.

Example code –

Python3

# import requests module

import requests

# Making a get request

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

# print response

print(response)

# print headers of response

print(response.headers)

Example Implementation –

Save above file as request.py and run using

Python request.py

Output –

Response Methods - Python requests - GeeksforGeeks (5)

response.content

response.content returns the content of the response, in bytes. Basically, it refers to Binary Response content.

How to use response.content using Python requests?

To illustrate use of response.content, let’s ping API of Github. To run this script, you need to have Python and requests installed on your PC.

Example code –

Python3

import requests

# Making a get request

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

# printing request content

print(response.content)

Example Implementation –

Save above file as request.py and run using

Python request.py

Output –

Response Methods - Python requests - GeeksforGeeks (6)

Check that b’ at the start of output, it means the reference to a bytes object.



N

NaveenArora

Response Methods - Python requests - GeeksforGeeks (7)

Improve

Next Article

response.ok - Python requests

Please Login to comment...

Response Methods - Python requests - GeeksforGeeks (2024)
Top Articles
Spaceships and Rockets - NASA
REER And NEER - Defintion, Formula, Differences & Importance
55Th And Kedzie Elite Staffing
It's Official: Sabrina Carpenter's Bangs Are Taking Over TikTok
Minooka Channahon Patch
Palm Coast Permits Online
Odawa Hypixel
<i>1883</i>'s Isabel May Opens Up About the <i>Yellowstone</i> Prequel
Women's Beauty Parlour Near Me
How Far Is Chattanooga From Here
Espn Expert Picks Week 2
Baseball-Reference Com
Premier Boating Center Conroe
Vichatter Gifs
Conduent Connect Feps Login
De Leerling Watch Online
Walthampatch
The most iconic acting lineages in cinema history
Lima Funeral Home Bristol Ri Obituaries
Eka Vore Portal
Most McDonald's by Country 2024
Skyward Login Jennings County
Fsga Golf
Holiday Gift Bearer In Egypt
Gotcha Rva 2022
Drift Hunters - Play Unblocked Game Online
Breckiehill Shower Cucumber
Renfield Showtimes Near Paragon Theaters - Coral Square
Craftsman Yt3000 Oil Capacity
Darktide Terrifying Barrage
Gideon Nicole Riddley Read Online Free
Ket2 Schedule
Msnl Seeds
Latest Nigerian Music (Next 2020)
Main Street Station Coshocton Menu
Uc Santa Cruz Events
Dollar Tree's 1,000 store closure tells the perils of poor acquisitions
Myanswers Com Abc Resources
Leena Snoubar Net Worth
Hireright Applicant Center Login
What Is A K 56 Pink Pill?
11526 Lake Ave Cleveland Oh 44102
2132815089
SF bay area cars & trucks "chevrolet 50" - craigslist
Post A Bid Monticello Mn
Valls family wants to build a hotel near Versailles Restaurant
Iman Fashion Clearance
Tyco Forums
Horseneck Beach State Reservation Water Temperature
Coleman Funeral Home Olive Branch Ms Obituaries
Bumgarner Funeral Home Troy Nc Obituaries
Latest Posts
Article information

Author: Stevie Stamm

Last Updated:

Views: 5957

Rating: 5 / 5 (60 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Stevie Stamm

Birthday: 1996-06-22

Address: Apt. 419 4200 Sipes Estate, East Delmerview, WY 05617

Phone: +342332224300

Job: Future Advertising Analyst

Hobby: Leather crafting, Puzzles, Leather crafting, scrapbook, Urban exploration, Cabaret, Skateboarding

Introduction: My name is Stevie Stamm, I am a colorful, sparkling, splendid, vast, open, hilarious, tender person who loves writing and wants to share my knowledge and understanding with you.