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
The Best Time to Shop at Aldi
What Is Data Privacy? | Definition from TechTarget
Usborne Links
Craigslist Vermillion South Dakota
Paketshops | PAKET.net
Dityship
Es.cvs.com/Otchs/Devoted
Koop hier ‘verloren pakketten’, een nieuwe Italiaanse zaak en dit wil je ook even weten - indebuurt Utrecht
All Buttons In Blox Fruits
Craigslist Farm And Garden Tallahassee Florida
Crossword Nexus Solver
Leader Times Obituaries Liberal Ks
Is Grande Internet Down In My Area
Invert Clipping Mask Illustrator
Missouri Highway Patrol Crash
Gayla Glenn Harris County Texas Update
Td Small Business Banking Login
Where Is George The Pet Collector
Hewn New Bedford
Mail.zsthost Change Password
Egizi Funeral Home Turnersville Nj
Johnnie Walker Double Black Costco
Baldur's Gate 3: Should You Obey Vlaakith?
Myql Loan Login
Move Relearner Infinite Fusion
Villano Antillano Desnuda
Tim Steele Taylorsville Nc
Pioneer Library Overdrive
Downloahub
Pipa Mountain Hot Pot渝味晓宇重庆老火锅 Menu
Laveen Modern Dentistry And Orthodontics Laveen Village Az
Jeep Cherokee For Sale By Owner Craigslist
The Pretty Kitty Tanglewood
Muma Eric Rice San Mateo
Heelyqutii
Unifi Vlan Only Network
Sukihana Backshots
Improving curriculum alignment and achieving learning goals by making the curriculum visible | Semantic Scholar
Satucket Lectionary
'The Night Agent' Star Luciane Buchanan's Dating Life Is a Mystery
Mynord
Ferhnvi
Iman Fashion Clearance
Euro area international trade in goods surplus €21.2 bn
Enter The Gungeon Gunther
Bellelement.com Review: Real Store or A Scam? Read This
Rick And Morty Soap2Day
Public Broadcasting Service Clg Wiki
Cool Math Games Bucketball
Shad Base Elevator
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.