How to use requests to send a PATCH request with headers

39,360

patch takes kwargs, just pass headers = {your_header}:

def patch(url, data=None, **kwargs):
    """Sends a PATCH request.

    :param url: URL for the new :class:`Request` object.
    :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response
    """

    return request('patch', url,  data=data, **kwargs)

Sosomething like:

head = {"Authorization":"Token token=xxxxxxxxxxxxxxxxxxxxxx"}
url = 'http://0.0.0.0:3000/api/v1/update_experiment.json'
payload = {'expt_name' : 'A60E001', 'status' : 'done' }

r = requests.patch(url, payload, headers=head)
Share:
39,360
Bart C
Author by

Bart C

Updated on July 17, 2022

Comments

  • Bart C
    Bart C almost 2 years

    I have a Rails 4 application which uses token based authentication for APIs and need to be able to update records through Python 3 script.

    My current script looks like this

    import requests
    import json
    
    url = 'http://0.0.0.0:3000/api/v1/update_experiment.json'
    payload = {'expt_name' : 'A60E001', 'status' : 'done' }
    
    r = requests.patch(url, payload)
    

    which works OK if I disable API authentication.

    I can't figure out how to add headers to it, requests.patch only takes two parameters according to docs.

    I would need to get to the point where the following header info would added

    'Authorization:Token token="xxxxxxxxxxxxxxxxxxxxxx"'
    

    This type of header works OK in curl. How can I do this in Python 3 and requests?