Welcome to Tesla Motors Club
Discuss Tesla's Model S, Model 3, Model X, Model Y, Cybertruck, Roadster and More.
Register

REST API SWIFT

This site may earn commission on affiliate links.

NicB72

Member
Supporting Member
Jun 25, 2016
103
62
Concord, MA
So, I have read through all 81 pages of the REST API thread and not found an answer.

I am new to SWIFT and trying to use the REST API. Getting stuck at the auth component.
I have read Tesla Model S JSON API · Apiary

and I know its....

POST https://owner-api.teslamotors.com/oauth/token
Attributes
  • grant_type
  • client_id
  • client_secret
  • email
  • password

So I am doing the usual

let url = NSURL(string: "https://owner-api.teslamotors.com/oauth/token")!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("password", forHTTPHeaderField: "grant_type")

and setting the rest of the header values
But I get back...

"Www-Authenticate" = "Bearer realm=\"Doorkeeper\", error=\"invalid_request\", error_description=\"The request is missing a required parameter, includes an unsupported parameter value, or is otherwise malformed.\"";



Optional("{\"error\":\"invalid_request\",\"error_description\":\"The request is missing a required parameter, includes an unsupported parameter value, or is otherwise malformed.\"}")
 
// Using OS X Playground

import XCPlayground
import Cocoa
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true

let url = NSURL(string: "https://owner-api.teslamotors.com/oauth/token")!
let request = NSMutableURLRequest(URL: url)
var stringPost = "grant_type=password&client_id=aaaaa&client_secret=bbbbbb&[email protected]&password=zzzzzz"
request.HTTPMethod = "POST"
let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = data
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { data, response, error in
if let response = response, data = data {
print(response)
print(String(data: data, encoding: NSUTF8StringEncoding))
} else {
print(error)
}
}

task.resume()

This seems to work with the right client_id, client_secret, email and password as @fact200 indicated.