Requirements
Note: We will use httpbin.org in this post. httpbin.org is a web service that allows us to test the HTTP request.
Install Python Requests Package
pip install requests
To verify installation, run following command in Python shell...
import requests
Python Http Get request
import requests
r = requests.get('https://www.github.com')
print(r.status_code)
Output of above code...
200
To extract the html of the website just do r.text
text = r.text
To look at other options, just do r.<tab>
r.headers will give you all the headers information.
r.headers
Python Get Requests Pass Parameters
import requests
payload = {'user_name': 'test', 'password': 'test'}
r = requests.post("http://httpbin.org/post", data=payload)
print(r.url)
print(r.text)
Python POST Requests
Post requests are used to post data to server.
import requests
payload = {'user_name': 'test', 'password': 'test'}
r = requests.post("http://httpbin.org/post", data=payload)
print(r.url)
print(r.text)
Python Post Json
Method 1
We can also post Json data using Python requests.
jsonData = {
"id": 1,
"name":"John"
}
requests.post('https://httpbin.org/post', json=jsonData)
Method 2
We can also pass in headers and let the receiving side know that data is in Json form.
import requests
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
response = requests.post('https://httpbin.org/post',
data={'id': 1, 'name': 'John'},
headers=headers)
print("Status code: ", response.status_code)
response_Json = response.json()
print("Printing Post JSON data")
print(response_Json['data'])
print("Content-Type is ", response_Json['headers']['Content-Type'])
Output of above code is...
Status code: 200
{"id": 1, "name": "John"}
Content Type is application/json