Home > Software engineering >  How to pass data into header while using URLSession in Swift?
How to pass data into header while using URLSession in Swift?

Time:02-18

I am new to swift and am in the learning phase.

I have to basically make a request using URLSession but the API does not allow any unauthorized requests

here is my code :

func getCoinPrice(for currency: String) {
    
    let urlString = baseURL   currency
    
    guard let url = URL(string: urlString) else {
        return
    }
    var request = URLRequest(url: url)
    request.setValue(apiKey, forHTTPHeaderField: "x-api-key")
    
    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
        if error != nil {
            print(error!)
            return
        }
        let dataAsString = String(data: data!, encoding: .utf8)
        print(dataAsString ?? "NO VALUE")
    }
    task.resume()
}

I have the line request.setValue(apiKey, forHTTPHeaderField: "CoinAPI-Key") where I am passing the APIkey but strangely I always get this response

{
  "error": "You didn\u0027t specify API key or it is incorrectly formatted. You should do it in query string parameter \u0060apikey\u0060 or in http header named \u0060X-CoinAPI-Key\u0060"
}

The same request in header works perfectly in Postman as you can see below enter image description here

what am I doing wrong? any help would be appreciated

modification of code (still get same error) :

func getCoinPrice(for currency: String) {
    
    let urlString = baseURL   currency
    
    var urlComponent = URLComponents(string: urlString)
    
    urlComponent?.queryItems = [URLQueryItem(name: apiKey, value: "x-api-key")]
    
    let request = URLRequest(url: urlComponent!.url!)
    
    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
        if error != nil {
            print(error!)
            return
        }
        let dataAsString = String(data: data!, encoding: .utf8)
        print(dataAsString ?? "NO VALUE")
    }
    task.resume()
}

CodePudding user response:

enter image description here

ok approach you're answer with this solution

enter image description here

  • Related