Making HTTP Request with header in Swift
Asked Answered
E

2

16

I am trying to make an HTTP request to the Imgur API. I am trying to retrieve all images associated with the tag "cats." The url, according to the Imgur API is: https://api.imgur.com/3/gallery/t/cats

the Imgur API states the following about the authorization needed to make get requests:

For public read-only and anonymous resources, such as getting image info, looking up user comments, etc. all you need to do is send an authorization header with your client_id in your requests. This also works if you'd like to upload images anonymously (without the image
being tied to an account), or if you'd like to create an anonymous
album. This lets us know which application is accessing the API.

Authorization: Client-ID YOUR_CLIENT_ID

I've looked at the following questions and tried things suggested there, but none of them have helped.

JSON NSURLRequest with credentials

Swift GET request with parameters

How to make a Http get and set httpHeader in Swift?

My current code is this:

let string = "https://api.imgur.com/3/gallery/t/cats"
let url = NSURL(string: string)
let request = NSMutableURLRequest(URL: url!)
request.setValue("clientIDhere", forHTTPHeaderField: "Authorization")
//request.addValue("clientIDhere", forHTTPHeaderField: "Authorization")
request.HTTPMethod = "GET"
let session = NSURLSession.sharedSession()

let tache = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
    if let antwort = response as? NSHTTPURLResponse {
        let code = antwort.statusCode
        print(code)
    }
}
tache.resume()

But I continually get a status code of 403, meaning authorization is required. What am I doing wrong?

Evaevacuant answered 4/1, 2016 at 2:13 Comment(2)
Something's amiss, perhaps in your problem description, because the Authorization Required code is 401: {"data":{"error":"Authentication required","request":"\/3\/gallery\/t\/cats","method":"GET"},"success":false,"status":401} when doing exactly the above unauth'd HTTP GET from Chrome browser. 403 is 'Forbidden' meaning no amount of authorization will allow you to get that page, it's just a locked off area.Diplo
when copy/pasting that url into the browser, I get the same response, status code of 401. But when running it in Xcode, the status code is 403. If I remove the request.setValue method in Xcode, the status code changes to 401.Evaevacuant
H
26

I think you need to prepend Client-ID string to your actual client ID as for the header value:

request.setValue("Client-ID <your_client_id>", forHTTPHeaderField: "Authorization")
Honghonied answered 4/1, 2016 at 2:22 Comment(1)
Can you help me. I am doing the same thing for google books api but i am getting Invalid Credentials. Please let me know if you can help me.Fruitless
I
5

Updated for swift 4 :

func fetchPhotoRequest(YOUR_CLIENT_ID: String)  {
    let string = "https://photoslibrary.googleapis.com/v1/albums"
    let url = NSURL(string: string)
    let request = NSMutableURLRequest(url: url! as URL)
    request.setValue(YOUR_CLIENT_ID, forHTTPHeaderField: "Authorization") //**
    request.httpMethod = "GET"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    let session = URLSession.shared

    let mData = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
        if let res = response as? HTTPURLResponse {
            print("res: \(String(describing: res))")
            print("Response: \(String(describing: response))")
        }else{
            print("Error: \(String(describing: error))")
        }
    }
    mData.resume()
}
Inferior answered 16/10, 2018 at 9:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.