4.5.2.REST APIs & HTTP Requests - sj50179/IBM-Data-Science-Professional-Certificate GitHub Wiki
- Scheme : the protocol, for this lab it will always be http://
- Internet address or Base URL : used to find the location, for example, 'www.ibm.com' or 'www.gitlab.com'
- Route : location on the web server, for example, '/images/IDSNlogo.png'
- GET : retrieves data from the server
- POST : submits data to server
- PUT : updates data already on server
- DELETE : deletes data from server
import requests
url = 'https://www.ibm.com/'
r = requests.get(url)
r.status_code:200
r.request.headers
{'User-Agent': 'python-requests/2.24.0', ..........}
r.request.body:None
header = r.headers
header:
{'Server': 'Apache', 'x-drupal-dynamic-cache': 'UNCACHEABLE', .....}
header['date']:'Thu, 19 Nov 2020 15:21:47 GMT'
header['Content-Type']:'text/html; charset=UTF-8'
r.encoding:'UTF-8'
r.text[0:100]:
'<!DOCTYPE html>\n<html lang="en-ca" dir='ltr">\n <head>\n
<meta charset="utf-8" />\n<script>digitalD'
Query string
Start of Query | Parameter Name | Value | Parameter Name | value | |||
---|---|---|---|---|---|---|---|
? | name | = | Joseph | & | ID | = | 123 |
http://httpbin.org/get?name=Joseph&ID=123
Create Query string
url_get='http://httpbin.org/get'
payload-{"name":"Joseph","ID":"123"}
r=requsets.get(url_get,params=payload)
r.url:'http://httpbin.org/get?name=Joseph&ID=123'
r.request.body:None
r.status_code:200
r.text ...
r.headers['Content-Type'] -> 'application/json'
r.json() ...
r.json()['args'] -> {'ID' : '123', 'name' : 'Joseph'}
POST
url_post="http://httpbin.org/post"
payload={"name" : "Joseph", "ID" : "123"}
r_post=requests.post(url_post, data=payload)
Compare POST and GET
print("POST request URL:", r_post.url)
print("GET request URL:", r.url)
POST request url: http://httpbin.org/post
GET request URL: http://httpbin.org/get?name=Joseph&ID=123
print("POST request body:", r_post.request.body)
print("GET request body:", r.request.body)
POST request body: name=Joseph&ID=123
GET request body: None
r_post.json()['fomr']
{'ID' : '123', 'name' : 'Joseph'}