zrbecker
zrbecker

Reputation: 1582

httplib failing when requesting from digitalocean api

I am playing around with the digital ocean api, and I wanted to be able to send an HTTP request and get a response in python to it. However I keep getting a 301 Moved Permanently. When I do it with curl it works fine. However when inspecting the actual HTTP headers, it looks like I am sending the same request, except user-agent. Can anyone tell me what I am doing wrong?

The curl command I am using is

curl -v -X GET "https://api.digitalocean.com/v2/actions" \
  -H "Authorization: Bearer secret"

Here is my python code.

import httplib

token = 'secret'
hostname = 'api.digitalocean.com'
conn = httplib.HTTPConnection(hostname)

conn.set_debuglevel(1)

conn.connect()
conn.putrequest('GET', '/v2/actions', skip_accept_encoding=True)
conn.putheader('Accept', '*/*')
conn.putheader('User-Agent', 'TestProgram')
conn.putheader('Authorization', 'Bearer ' + token)
conn.endheaders()
conn.send('')

response = conn.getresponse()

print response.read()
print response.getheaders()

conn.close()

Upvotes: 0

Views: 68

Answers (1)

xiaket
xiaket

Reputation: 2083

Please note that by using:

conn = httplib.HTTPConnection(hostname)

You are creating an HTTP connection, and DO is using an HTTP redirect to ask you to use https://api.digitalocean.com/.

$ wget -S 'http://api.digitalocean.com'
--2017-01-10 16:41:14--  http://api.digitalocean.com/
Resolving api.digitalocean.com... 104.16.24.4, 104.16.25.4
Connecting to api.digitalocean.com|104.16.24.4|:80... connected.
HTTP request sent, awaiting response...
  HTTP/1.1 301 Moved Permanently
  Location: https://api.digitalocean.com/
Location: https://api.digitalocean.com/

By the way, please stop using httplib, instead, please use requests.

Upvotes: 1

Related Questions