Introduction
In this article, we'll talk about the Python implementations of the GET and POST HTTP (Hypertext Transfer Protocol) request methods.
What is HTTP?
A group of protocols known as HTTP are used to facilitate client-server communication. It functions as a client-server request-response protocol.
The client could be a web browser, and the server could be an application running on the computer that is hosting the website.
To request a response from the server, there are mainly two methods:
- GET: To get the response from the server.
- POST: To submit the data to the server.
The most simplest of all listed libraries is Requests. We will be using requests library to implement GET and POST request in this article.
You can install requests library using the following command:
Make a GET Request
We can make a GET request using get() method:
Example 1:
# import requests module import requests from requests.auth import HTTPBasicAuth
# Making a get request response = requests.get('https://api.github.com / user, ', auth = HTTPBasicAuth('user', 'pass'))
# print request object print(response) |
Output:
Example 2
# 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) |
Output:
https://api.github.com/ 200 |
Make a POST Request
We can make a POST request using post() method:
Example 1:
import requests in_values = {'username':'Buck','password':'Zero'} res = requests.post('https://httpbin.org/post',data = in_values) print(res.text) |
Output:
{ "args": {}, "data": "", "files": {}, "form": { "password": "Zero", "username": "Buck" }, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Content-Length": "27", "Content-Type": "application/x-www-form-urlencoded", "Host": "httpbin.org", "User-Agent": "python-requests/2.27.1", "X-Amzn-Trace-Id": "Root=1-6392283e-609fd46c4d7fb71a3d00fd25" }, "json": null, "origin": "162.55.95.48", "url": "https://httpbin.org/post" } |