0

I am trying to request an API in order to get response data. I need to add to headers in the request what I have done using request.addValue(""). It works fine when I am using postman. But I don't why I got no data with Xcode. The response is 403 Forbidden

class Service {
    private static let sUrl = URL(string: "https://bff-mobile-dev.XXXXX.com/demands/filter")!

static func getData() {
    var request = URLRequest(url: sUrl)

    request.httpMethod = "POST"
    let session = URLSession(configuration: .default)
    request.addValue("Accept-Version", forHTTPHeaderField: "3.0.0")
    request.addValue("X-Request-Id", forHTTPHeaderField: "057BC3BD-46E1-4125-9F3B-23805CA3132F")

    let task = session.dataTask(with: request) { (data, response, error) in
        if let data = data, error == nil {
            if let response = response as? HTTPURLResponse {
                print(response)
            }
        }
    }
    task.resume()

}
} 
kroko
  • 299
  • 3
  • 10
  • Check this https://stackoverflow.com/questions/26364914/http-request-in-swift-with-post-method – Sailendra Dec 20 '19 at 08:25
  • 403 means you are forbidden to access the resource at that location. The reasons why are varied. I've seen it mostly in relation to cross site referrals but also with respect to invalid or missing session cookies, attempting to access a directory when directory access is disabled, using a not allowed method and several other reasons. You have to find out why your request is forbidden to fix it. Maybe the body of the response has some more information. – JeremyP Dec 20 '19 at 08:34
  • Have you not got your key and value mixed up in when you added the headers? – SWAT Dec 20 '19 at 08:43
  • @JeremyP He is getting 403 because the server could not read the header field that he just added and authenticate the request. He most likely got the key value pair mixed up. See my answer. – SWAT Dec 20 '19 at 08:48
  • @SWAT you are right about confusing the key and value, but my point still stands as a general point about 403 errors. – JeremyP Dec 20 '19 at 13:59

3 Answers3

1

I believe your key value pair is mixed up when you added the header fields.

request.setValue(value,forHTTPHeaderField: "HeaderFieldName")

Adding like this works.

SWAT
  • 1,107
  • 8
  • 19
1

I think that you inverted values of you header; they should be like this

request.addValue("3.0.0", forHTTPHeaderField: "Accept-Version")
request.addValue("057BC3BD-46E1-4125-9F3B-23805CA3132F", forHTTPHeaderField: "X-Request-Id")
Rico Crescenzio
  • 3,952
  • 1
  • 14
  • 28
0

Try something like below

var headerData:[String:String] = [:]
headerData["Accept-Version"] = "3.0.0"
headerData["X-Request-Id"] = "057BC3BD-46E1-4125-9F3B-23805CA3132F"
request.allHTTPHeaderFields = headerData
Yogesh Tandel
  • 1,738
  • 1
  • 19
  • 25