24

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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Bart C
  • 1,509
  • 2
  • 16
  • 17
  • Did you actually *try* adding `headers=`? What happened? – jonrsharpe Jun 23 '16 at 14:00
  • I tired something like `headers= {'Authorization': 'Token', 'token': 'xxxxxx' }` then `r = requests.patch(url, payload, headers=headers)` but nothing happens, no error in Python, no reaction from WebRick on Rails side. Trying to play with logs to see what it going on. – Bart C Jun 23 '16 at 14:46

1 Answers1

25

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)
Tajinder Singh
  • 1,361
  • 2
  • 14
  • 26
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • 1
    Hi. I tried `headers= {'Authorization': 'Token', 'token': 'xxxxxx' }` then `r = requests.patch(url, payload, headers=headers)` but Rails doesn't seem to like this. Authentication fails. How can I see what Python is actually sending, how to inspect the header. I tied `print(r.headers)` but this doesn't include any of the info I passed in as headers. – Bart C Jun 23 '16 at 15:02
  • @BartC note that that isn't quite the format of the headers - re-read that last code snippet. – jonrsharpe Jun 23 '16 at 15:04
  • 1
    @PadraicCunningham Enormous Thanks!!!!, that worked great, missed that detail / just didn't get it which was the culprit all along in many of my other attempts to make it work. Thanks again. – Bart C Jun 23 '16 at 15:34