Using Yelp Fusion API in swift app not authenticating, continuously receiving "VALIDATION_ERROR"

293 views Asked by At

Code here

let link = "https://api.yelp.com/oauth2/token"
guard let url = URL(string: link) else { return }

// Headers
let headers = [
  "content-type": "application/x-www-form-urlencoded"
]

guard let clientID = infoPlist(withKey: "YELP_API_CLIENT_ID"),
  let clientSecret = infoPlist(withKey: "YELP_API_CLIENT_SECRET") else { return }

let body = "client_id=\(clientID)&client_secret=\(clientSecret)&grant_type=client_credentials"

var request = URLRequest.init(url: url)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = body.data(using: .utf8)

As far as I know this should be working. Based on everything I've read this is the proper process for authenticating with Yelp Fusion/v3.

1

There are 1 answers

1
nathan On

You didn't post your entire code, but with some slight modifications your code works:

let appId = "xxx"
let appSecret = "yyy"
let link = "https://api.yelp.com/oauth2/token"
let url = URL(string: link)!

let bodyData = "client_id=\(appId)&client_secret=\(appSecret)&grant_type=client_credentials".data(using: .utf8)!

// Headers
let headers = [
    "Content-Type": "application/x-www-form-urlencoded",
    "Content-Length": "\(bodyData.count)"
]

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = bodyData

typealias JSON = [String:Any]
URLSession.shared.dataTask(with: request) { (data, response, error) in

    guard let data = data,
        let httpResponse = response as? HTTPURLResponse,
        httpResponse.statusCode == 200 else {
            print(error!)
            return
    }

    if let responseJSON = try? JSONSerialization.jsonObject(with:data, options:[]),
        let parsedJSON = responseJSON as? JSON {
        let token = parsedJSON["access_token"]
        let exipration = parsedJSON["expires_in"]
    }
}.resume()