0

I am trying to generate a voucher from Ubiquity UNIFY web portal. It has a API, and there is some ideas to use this with PHP, but I would like to use Python 2.6 to generate.. (I can ofc ourse use other Python versions if this is a must)

My code is:

import urllib, json
import urllib2
import unifi
import os
import requests

def JsonLogin():
    payload = {"username" : "myuser","password" : "mypassword"}
    r = requests.post("https://ubnt.myserver.com:8443/api/login", data=payload, verify=False)
    print r

def JsonApi():
    payload = {"cmd":"create-voucher","minutes":1440,"n":1}
    r = requests.post("https://ubnt.myserver.com:8443/api/cmd/hotspot", data=payload, verify=False)
    print r

JsonLogin();
JsonApi();

My Result is:

   <Response [400]>
   <Response [401]>

Is there any logic why it returns 400, witch means error... Is this because I sent invalid JSON or is this because the syntax or JSON tags are wrong?

Aurora0001
  • 13,139
  • 5
  • 50
  • 53
Eddie
  • 3
  • 3
  • Is the payload supposed to be a JSON string? If so you will need to encode it with `json.dumps` as suggested by this [section in the `requests` quick start guide](http://docs.python-requests.org/en/master/user/quickstart/#more-complicated-post-requests) – metatoaster Apr 01 '17 at 11:59
  • good question.. i am not that "good" .. – Eddie Apr 01 '17 at 12:01
  • https://github.com/malle-pietje/Unifi-API-browser/blob/master/phpapi/class.unifi.php#L1078-L1088' – Eddie Apr 01 '17 at 12:01
  • the print r.text gives - { "data" : [ ] , "meta" : { "msg" : "api.err.Invalid" , "rc" : "error"}} – Eddie Apr 01 '17 at 12:03
  • 400 means bad request, and 401 means authorized failed. – stamaimer Apr 01 '17 at 12:07

1 Answers1

0

try this

payload= '{"username" : "myuser","password" : "mypassword", "strict":true}' r = requests.post("https://ubnt.myserver.com:8443/api/login", data=payload, verify=False) print r

It should return 200

Then set someway the cookie value that the login returns into a variable cookies=r.cookies

then

r = requests.post("https://ubnt.myserver.com:8443/api/cmd/hotspot", data=payload, verify=False, cookies=cookies)

I used it with GET and it works