Open peter2680 opened 4 months ago
## HTTP and Requests
import requests
import os
from PIL import Image
from IPython.display import IFrame
url='https://www.ibm.com/'
r=requests.get(url)
r.status_code
print(r.request.headers)
print("request body:", r.request.body)
header=r.headers
print(r.headers)
# Use single quotation marks for defining string
url='https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/IDSNlogo.png'
path=os.path.join(os.getcwd(),'image.png')
with open(path,'wb') as f:
f.write(r.content)
Image.open(path)
Click here for the solution
url='https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%205/data/Example1.txt'
path=os.path.join(os.getcwd(),'example1.txt')
r=requests.get(url)
with open(path,'wb') as f:
f.write(r.content)
url_get='http://httpbin.org/get'
r=requests.get(url_get,params=payload)
print("request body:", r.request.body)
Post Requests
Like a GET request, a POST is used to send data to a server, but the POST request sends the data in a request body. In order to send the Post Request in Python, in the URL we change the route to POST:
url_post='http://httpbin.org/post'
This endpoint will expect data as a file or as a form. A form is convenient way to configure an HTTP request to send data to a server.
To make a POST request we use the post() function, the variable payload is passed to the parameter data :
r_post=requests.post(url_post,data=payload)
Comparing the URL from the response object of the GET and POST request we see the POST request has no name or value pairs.
print("POST request URL:",r_post.url )
print("GET request URL:",r.url)
We can compare the POST and GET request body, we see only the POST request has a body:
print("POST request body:",r_post.request.body)
print("GET request body:",r.request.body)
We can view the form as well:
r_post.json()['form']