Python Requests Post Get Status Code
When using Python requests library, you may need to make POST or GET requests to a server to retrieve or send data. In such cases, you also need to check the status code of the response to verify if the request was successful or not. The status code is a three-digit number that indicates the HTTP response status, such as 200, 404, 500, etc.
Using Requests GET Method
To use the GET method in Python requests, you need to import the library and use the get() function with the URL of the resource you want to retrieve. Here is an example:
import requests
response = requests.get("https://www.example.com")
print(response.status_code)
This will retrieve the homepage of www.example.com and print the status code of the response. If the request was successful, it should print 200.
Using Requests POST Method
To use the POST method in Python requests, you need to import the library and use the post() function with the URL of the resource you want to send data to and the data you want to send. Here is an example:
import requests
payload = {"username": "example_user", "password": "example_pass"}
response = requests.post("https://www.example.com/login", data=payload)
print(response.status_code)
This will send a POST request to www.example.com/login with the username and password data and print the status code of the response. If the login was successful, it should print 200.
Handling Exceptions
When making requests with Python requests library, there may be exceptions that can occur. It's important to handle these exceptions properly to avoid errors in your code. Here is an example of handling exceptions:
import requests
try:
response = requests.get("https://www.example.com")
response.raise_for_status()
except requests.exceptions.HTTPError as err:
print(err)
else:
print(response.status_code)
In this example, we use a try-except block to catch any HTTP errors that may occur during the request. If there are no errors, it will print the status code of the response.
Conclusion
Python requests library is a powerful tool for making HTTP requests in Python. By using the GET and POST methods, you can easily retrieve or send data to a server. Checking the status code of the response is important to verify if the request was successful or not. Always handle exceptions properly to avoid errors in your code.