Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use requests to send a PATCH request with headers

Tags:

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?

like image 984
Bart C Avatar asked Jun 23 '16 13:06

Bart C


1 Answers

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)

So something like this:

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)
like image 140
Padraic Cunningham Avatar answered Oct 01 '22 13:10

Padraic Cunningham