Request method

  • GET View resources.
  • POST adding resources
  • PUT Modifying resources
  • DELETE DELETE a resource
  • HEAD View the response header
  • OPTIONS View available request methodsrequests.[method](url)

Making the API sample

https://developer.github.com/v3/migrations/users/

  • json.load()Decodes the encoded JSON string into a Python object
def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None,
        parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
    """Deserialize ``s`` (a ``str`` instance containing a JSON document) to a Python object.Copy the code
  • json.dumps()Encode Python objects as JSON strings
def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
        allow_nan=True, cls=None, indent=None, separators=None,
        default=None, sort_keys=False, **kw):
    """Serialize ``obj`` to a JSON formatted ``str``.
Copy the code
  • encodeEncode Python objects as JSON strings
  • decodeDecodes the encoded JSON string into a Python object
URL = 'https://api.github.com'

def build_uri(endpoint):
    return '/'.join([URL, endpoint])

def better_print(json_str):
    """Deserialize ``s`` (a ``str`` instance containing a JSON document) to a Python object."""
    return json.dumps(json.loads(json_str), indent=4)

def request_method():
    response = requests.get(build_uri('user/emails'), auth=('user'.'psw'))
    print(response.status_code)
    print(better_print(response.text))
>>[
  {
    "email": "[email protected]"."verified": true."primary": true."visibility": "public"}]Copy the code

Github modifies user information

  • PATCH /user
  • Note: If your email is set to private and you send an email parameter as part of this request to update your profile, your privacy settings are still enforced: the email address will not be displayed on your public profile or via the API.
  • response = requests.patch(url, auth=('user', 'psw'), json={'name':'123'})

Request Exception Handling

Request. get(URL,timeout=timeout) #timeout=(x1,x2) Limit the request-response duration individually for each step #timeout=x Limit the request-response duration overall

from requests import exceptions
def timeout_request():
    try:
        response = requests.get(build_uri('user/emails'),timeout=10)
    except exceptions.Timeout as e:
        print(str(e))
    else:
        print(response.text)
Copy the code

Custom Requests

def hard_request():
    from requests import  Request, Session
    s = Session()
    headers = {'User-Agent': 'fake1.3.4'}
    req = Request('GET',build_uri('user/emails'), auth=('user'.'psw'),
                  headers = headers)
    prepped = req.prepare()
    print(prepped.body)
    print(prepped.headers)
    resp = s.send(prepped, timeout=5)
    print(resp.status_code)
    print(resp.headers)
    print(resp.text)
Copy the code

About the user-agent

The user-Agent tells the site server what tool the visitor is using to make the request, and generally rejects it if it’s a crawler request, and responds if it’s a User’s browser.