Home > Software engineering >  Send GET request with bearer token and json body in SWift
Send GET request with bearer token and json body in SWift

Time:11-09

I'm new to swift and I tried to make a get request to a api, but couldn't come up with an working result yet. All examples I tried but not worked at all

I need to send a json body to https://pincood.com/pincood/public/api/user/details and in Authorization I passed Bearer token like this "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjIsImlzcyI6Imh0dHBzOi8vcGluY29vZC5jb20vcGluY29vZC9wdWJsaWMvYXBpL3VzZXIvbG9naW4iLCJpYXQiOjE2Njc4MjMxNzAsImV4cCI6MTY2ODE4MzE3MCwibmJmIjoxNjY3ODIzMTcwLCJqdGkiOiJVemo4bFp3ek16Z2FIV25QIn0.oCAk6db9c2BAhEGgU2gziYm2RX3hLbAtPUc7KQzIYWs" with GET request.

And in the output the data will display like this:

The json body only contains of one value

{ "id": 2, "referral_code": "pn7R7m", "referance_referral_code": "", "first_name": "Uzma", "last_name": "ansari", "payment_mode": "CASH", "email": "", "gender": "MALE", "birth_date": "2022-06-23", "mobile": "9326257573", "country_code": " 91", "picture": "https://pincood.com/pincood/public/storage/user/profile/9326257573.png", "device_token": "dW_jfRo94fM:APA91bFluxLzYICoYw6MslhYWEzxET8NYKH27MzSmQNRT6fNLdo6eAIB6KBZv9IvkFrSHUA2GUD1RfNw1e2XVdIdSZjDf-627PRLopzOwInifGdWIA4k-nIwLDghycCAlhwW0KJy76Xe", "device_id": "ceae4b934e63a578", "device_type": "android", "login_by": "manual", "social_unique_id": null, "latitude": null, "longitude": null, "stripe_cust_id": null, "wallet_balance": 0, "rating": "5.00", "otp": 811078, "updated_at": "2022-11-06 12:44:01", "emergency_contact1": "9999999999", "emergency_contact2": "", "deleted_at": null, "currency": "₹", "sos": "911", "rental_content": "Dummy Content", "outstation_content": "Dummy Content" }

And I tried in the implementation like this My Model :

struct TokenResponse: Codable { let id : Int let referral_code: String let referance_referral_code: String let first_name: String let last_name: String let payment_mode: String let email: String let gender: String let birth_date: String let mobile: String let country_code: String let picture: String let device_token: String let device_id: String let device_type: String let login_by: String let social_unique_id: String let latitude: String let longitude: String let stripe_cust_id: String let wallet_balance: Int let rating: String let otp: Int let updated_at: String let emergency_contact1: String let emergency_contact2: String let deleted_at: String let currency: String let sos: String let rental_content: String let outstation_content: String

enum CodingKeys: String, CodingKey {
    case id
    case referral_code
    case referance_referral_code
    case first_name
    case last_name
    case payment_mode
    case email, gender
    case birth_date
    case mobile
    case country_code
    case picture
    case device_token
    case device_id
    case device_type
    case login_by
    case social_unique_id
    case latitude, longitude
    case stripe_cust_id
    case wallet_balance
    case rating, otp
    case updated_at
    case emergency_contact1
    case emergency_contact2
    case deleted_at
    case currency, sos
    case rental_content
    case outstation_content
}

}

My function from where I trid to call my api

func getRequest(){
   let url = URL(string: "https://pincood.com/pincood/public/api/user/details/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjIsImlzcyI6Imh0dHBzOi8vcGluY29vZC5jb20vcGluY29vZC9wdWJsaWMvYXBpL3VzZXIvbG9naW4iLCJpYXQiOjE2Njc4MjMxNzAsImV4cCI6MTY2ODE4MzE3MCwibmJmIjoxNjY3ODIzMTcwLCJqdGkiOiJVemo4bFp3ek16Z2FIV25QIn0.oCAk6db9c2BAhEGgU2gziYm2RX3hLbAtPUc7KQzIYWs")!
var request = URLRequest(url: url)
request.allHTTPHeaderFields = [
  "Content-Type": "application/json",
  "Session": "fb4e7f9b-0f31-4709-",
  "AUthorization":"Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjIsImlzcyI6Imh0dHBzOi8vcGluY29vZC5jb20vcGluY29vZC9wdWJsaWMvYXBpL3VzZXIvbG9naW4iLCJpYXQiOjE2Njc4MjMxNzAsImV4cCI6MTY2ODE4MzE3MCwibmJmIjoxNjY3ODIzMTcwLCJqdGkiOiJVemo4bFp3ek16Z2FIV25QIn0.oCAk6db9c2BAhEGgU2gziYm2RX3hLbAtPUc7KQzIYWs"
]

URLSession.shared.dataTask(with: request) { (data, response, error) in
  guard error == nil else { return }
  guard let data = data, let _ = response else { return }
  // handle data
  do{
                    //here dataResponse received from a network request
                 let decoder = JSONDecoder()
                 let codabledata = try decoder.decode(TokenResponse.self, from: data)
                    print(codabledata)
                 //Response result
                //  Completion(codabledata)
                    
                } catch let parsingError {
                    print("Error", parsingError)
                }
}.resume()
}

getRequest()

CodePudding user response:

try this example code with the "modified" url string, and the corresponding data model that needs to match the json data you get from the server:

EDIT-1: with a callback from the asynchronous function.

Use it like this:

getRequest() { results in
    print(results)
}

func getRequest(callback: @escaping (TokenResponse?) -> Void) {
    let theToken =  "...."
    
    if let url = URL(string: "https://pincood.com/pincood/public/api/user/details") {
        var request = URLRequest(url: url)
        request.allHTTPHeaderFields = [
            "Content-Type": "application/json",
            "Session": "fb4e7f9b-0f31-4709-",
            "Authorization":"Bearer \(theToken)"
        ]
        
        URLSession.shared.dataTask(with: request) { (data, response, error) in
            guard error == nil else { return }
            guard let data = data else { return }
            do {
                let decoder = JSONDecoder()
                decoder.keyDecodingStrategy = .convertFromSnakeCase  // <-- here
                let codabledata = try decoder.decode(TokenResponse.self, from: data)
                callback(codabledata)  // <-- here
            } catch {
                print(error)
                callback(nil)  // <-- here
            }
        }.resume()
    }
}

and

struct TokenResponse: Codable {
    let id: Int
    let referralCode, referanceReferralCode, firstName, lastName: String
    let paymentMode, email, gender, birthDate: String
    let mobile, countryCode, picture, deviceToken: String
    let deviceId, deviceType, loginBy: String // <--
    let socialUniqueId, latitude, longitude, stripeCustId: String?  // <--
    let walletBalance: Int
    let rating: String
    let otp: Int
    let updatedAt, emergencyContact1, emergencyContact2: String
    let deletedAt: String?
    let currency, sos, rentalContent, outstationContent: String
}

You will need to consult the API docs to determine which properties are optional. In that case add ? to them.

EDIT-2: passing the token to the function:

func getRequest(token: String, callback: @escaping (TokenResponse?) -> Void) {
    if let url = URL(string: "https://pincood.com/pincood/public/api/user/details") {
        var request = URLRequest(url: url)
        request.allHTTPHeaderFields = [
            "Content-Type": "application/json",
            "Session": "fb4e7f9b-0f31-4709-",
            "Authorization":"Bearer \(token)"  // <-- here
        ]
        
        URLSession.shared.dataTask(with: request) { (data, response, error) in
            guard error == nil else { return }
            guard let data = data else { return }
            do {
                let decoder = JSONDecoder()
                decoder.keyDecodingStrategy = .convertFromSnakeCase
                let codabledata = try decoder.decode(TokenResponse.self, from: data)
                callback(codabledata)  // <-- here
            } catch {
                print(error)
                callback(nil)  // <-- here
            }
        }.resume()
    }
}

And use it like this:

getRequest(token: "your-token-here") { results in
    print(results)
}
  • Related