Learn Courses My Dashboard

How to use json response as parameter in another api post call?

I make a GET call and receive a json response. I need to use that json response as one parameter for a subsequent POST call.

I’ve tried to:
-parse the data into an object and pass the [object] as parameter
-parse the data into a string and pass the string as parameter
-parse the data as dict and pass the dict as parameter

but it’s not working, I believe it’s a data thing or a secret I’m missing

How do you use a json response as parameter for a subsequent api call?

    //MARK: - PIXLAB facedetect
    func facedetectGET(uploadedUrl: String) {
        
        
        var urlComponents = URLComponents(string: "https://api.pixlab.io/facedetect")
        
        urlComponents?.queryItems = [
            URLQueryItem(name: "img", value: uploadedUrl),
            URLQueryItem(name: "key", value: Constants.pixlabAPIkey),
        ]
        let url = urlComponents?.url
        
        if let url = url {
            
            // Create URL Request
            var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10.0)
            request.httpMethod = "GET"
            request.addValue("Bearer \(Constants.pixlabAPIkey)", forHTTPHeaderField: "Authorization")
            
            // Get URLSession
            let session = URLSession.shared
            
            // Create Data Task
            let dataTask = session.dataTask(with: request) { (data, response, error) in
                
                // Check that there isn't an error
                if error == nil {
                    
                    do {
                        
                        let json = try JSONSerialization.jsonObject(with: data!, options: [])
                        //make a dict
                        //let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [String: Any]
                        
                        print("SUCCESS: image detected")
                        print(json)
                        //make json a string utf8 so it can be used as parameter in next call
                        //let jsonString = String(data: json as! Data, encoding: .utf8)
                        
        
                   
                        //let jsonData = json.data(using: .utf8)!
                        
                        //parse json
                        //decode the json to an array of faces
                        let faces: [Face] = try! JSONDecoder().decode([Face].self, from: data!)
                        
                        let facesString = String(faces)
                        //use dispatch main sync queue??"bottom": Int,
                        
                        //mogrify call
                        mogrify(uploadedUrl: uploadedUrl, cord: faces)
                        
                    }
                    catch {
                        print(error)
                    }
                }
            }
            
            // Start the Data Task
            dataTask.resume()
        }
        
    }
    
    //MOGRIFY CALL
    func mogrify(uploadedUrl: String, cord: Any) {

        let mogrifyurl = URL(string: "https://api.pixlab.io/mogrify")!
        
        //let param: [Face] = result.faces
        let param: [String: Any] = ["img": uploadedUrl, "cord": cord]
        
        var request = URLRequest(url: mogrifyurl)
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("Bearer \(Constants.pixlabAPIkey)", forHTTPHeaderField: "Authorization")
        request.httpMethod = "POST"
        request.httpBody = try! JSONSerialization.data(withJSONObject: param, options: [])

        URLSession.shared.dataTask(with: request) { (data, response, error) in
            if error != nil {
                print(error!)
                return
            }
            do {
                let json = try JSONSerialization.jsonObject(with: data!)
                print(json)
            } catch {
                print("error")
            }
        }.resume()
    }

this is how pretty the response looks like after serialization

when I decode it and pass it looks like this

You pass the JSON as part of the body of the request

I tried to pass It as data as well but got

*** Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘Invalid type in JSON write (Foundation.__NSSwiftData)’

terminating with uncaught exception of type NSException

mogrify(uploadedUrl: uploadedUrl, cord: data!)

then in the post call

 func mogrify(uploadedUrl: String, cord: Data) {

        let mogrifyurl = URL(string: "https://api.pixlab.io/mogrify")!
        
        //let param: [Face] = result.faces
        let param: [String: Any] = ["img": uploadedUrl, "key": Constants.pixlabAPIkey, "cord": [cord]]
        
        var request = URLRequest(url: mogrifyurl)
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("Bearer \(Constants.pixlabAPIkey)", forHTTPHeaderField: "Authorization")
        request.httpMethod = "POST"
        request.httpBody = try! JSONSerialization.data(withJSONObject: param, options: [])

the caveat is that the POST Call needs the following parameters:
img = string
coordinates = json response from previous call
key = api key

then I tried to pass it as json and it worked

**let** json = **try** ! JSONSerialization.jsonObject(with: data!, options: [])

mogrify(uploadedUrl: uploadedUrl, cord: json)
 func mogrify(uploadedUrl: String, cord: Any) {
        
        let mogrifyurl = URL(string: "https://api.pixlab.io/mogrify")!
        
        //let param: [Face] = result.faces
        let param: [String: Any] = ["img": uploadedUrl, "key": Constants.pixlabAPIkey, "cord": [cord]]
        
        var request = URLRequest(url: mogrifyurl)
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("Bearer \(Constants.pixlabAPIkey)", forHTTPHeaderField: "Authorization")
        request.httpMethod = "POST"
        request.httpBody = try! JSONSerialization.data(withJSONObject: param, options: [])

but the response from the new call didn’t return a perfect result…looks like it’s not recognizing my cord input. They expect to get It in this format

and I’m passing

is there a way to extract an array inside a json response?

Do you not already have this information available at the time this function is being called?

Yes, you parse an array like you would any other JSON object.
The JSON your showing in the two screenshots are completely different though
There’s completely different keys.

Have you ever used Postman before? You can use it to verify exactly what you want to send to the API call, and then figure out how to write it in Swift. Rather than trying to figure out two things at once and not knowing which isn’t working.

thanks for the insight Mikaela,
I did lots of white magic, voodoo and lots of praying (aka try and error) and I made it work…

basically decoded the json data, then got an array subdata and encode it back into a data variable as input for the post call

 do {
                        
                        //decode the json to an array of faces
                        let cord = try! JSONDecoder().decode(Cord.self, from: data!)
                        print(cord.faces)
                        
                        let cordData = try! JSONEncoder().encode(cord.faces)
                        let coordinates = try JSONSerialization.jsonObject(with: cordData, options: [])
                        print(coordinates)
                        
                        //mogrify call
                        mogrify(uploadedUrl: uploadedUrl, cord: coordinates)
                        
                    }
                    catch {
                        print(error)
                    }

    //MOGRIFY CALL
    func mogrify(uploadedUrl: String, cord: Any) {
        
        let mogrifyurl = URL(string: "https://api.pixlab.io/mogrify")!
        
        //let param: [Face] = result.faces
        let param: [String: Any] = ["img": uploadedUrl, "key": Constants.pixlabAPIkey, "cord": cord]
        
        var request = URLRequest(url: mogrifyurl)
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("Bearer \(Constants.pixlabAPIkey)", forHTTPHeaderField: "Authorization")
        request.httpMethod = "POST"
        request.httpBody = try! JSONSerialization.data(withJSONObject: param, options: [])
        
        URLSession.shared.dataTask(with: request) { (data, response, error) in
            if error != nil {
                print(error!)
                return
            }
            do {
                let json = try JSONSerialization.jsonObject(with: data!)
                print("MOGRIFY response")
                print(json)
            } catch {
                print("error")
            }
        }.resume()
    }

it was worth to spend 2 days stuck on this as I became an expert in decoding, encoding (sort of)

This may also help too, for working with JSON