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

Time:09-23

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 enter image description here

and this is how it looks when I pass it as parameter enter image description here

CodePudding user response:

A POST needs the body as Data. If you're just forwarding the body of the GET to the body of the POST, it would be easiest to leave it as Data.

You could also deserialize the response into an object in your get, and then re-serialize it back into Data in the POST code, but why?

CodePudding user response:

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

maybe there is an easier and more elegant way but this works....

 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)
}

post call

//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()
}
  • Related