skip to Main Content

I am trying to run a post request to send an image to the ximilar app. Not even sure if my request is 100% correct. Each time I get the same response of:

https://api.ximilar.com/recognition/v2/classify/ } { Status Code: 400, Headers {
    "Content-Type" =     (
        "application/json"
    );
    Date =     (
        "Mon, 12 Apr 2021 04:02:58 GMT"
    );
    Server =     (
        "nginx/1.16.1"
    );
    "Strict-Transport-Security" =     (
        "max-age=31536000"
    );
    Vary =     (
        "Accept, Origin"
    );
    allow =     (
        "POST, OPTIONS"
    );
    "referrer-policy" =     (
        "same-origin"
    );
    "x-content-type-options" =     (
        nosniff
    );
    "x-frame-options" =     (
        DENY
    );
} }
{
    records =     (
        "Expected a list of items but got type "str"."
    );
}

My code: (not sure if the body values are written right.)

let url = URL(string: "https://api.ximilar.com/recognition/v2/classify/")!
var request = URLRequest(url: url)
                            
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Token __MyTOKEN__", forHTTPHeaderField: "Authorization")
                        
let body = [
    "task_id" : "c03c288b-a249-4b17-9f63-974c2f30beb9",
    "records" : "https://www.sticky.digital/wp-content/uploads/2013/11/img-6.jpg"
]

let bodyData = try? JSONSerialization.data(withJSONObject: body, options: [] )
                        
request.httpMethod = "POST"
request.httpBody = bodyData
                        
let session = URLSession.shared
                        
session.dataTask(with: request) { (data, response, error) in
    if let response = response {
         print(response)
    }
    if let data = data {
        do {
           let json = try JSONSerialization.jsonObject(with: data, options: [])
           print(json)
        } catch {
           print(error)
          }
        }

}.resume()

I want to be able to output the JSON response in the console.

Here is the code in curl which works fine:

curl -H "Content-Type: application/json" -H "authorization: Token __API_TOKEN__" https://api.vize.ai/v2/classify -d '{"task_id": "0a8c8186-aee8-47c8-9eaf-348103feb14d", "version": 2, "descriptor": 0, "records": [ {"_url": "__IMAGE URL HERE__" } ] }'

2

Answers


  1. The server is reporting an error for records:

    Expected a list of items but got type "str"

    It is saying that it was expecting an array of items for records, but only received a string. In your curl, records is an array of dictionaries with a single key, _url, but in Swift the value is just a string, consistent with what the error reported. You also supply version and descriptor in curl, but not in the Swift example.

    Thus, you might try:

    let body: [String: Any] = [
        "task_id" : "c03c288b-a249-4b17-9f63-974c2f30beb9",
        "version": 2,
        "descriptor": 0,
        "records" : [
            [
                "_url": "https://www.sticky.digital/wp-content/uploads/2013/11/img-6.jpg"
            ]
        ]
    ]
    

    Alternatively, you might define Encodable types as outlined in Encoding and Decoding Custom Types:

    struct XimilarRequest: Encodable {
        let taskId: String
        let version: Int
        let descriptor: Int
        let records: [XimilarRecord]
    }
    
    struct XimilarRecord: Encodable {
        let url: URL
    
        enum CodingKeys: String, CodingKey {
            case url = "_url"
        }
    }
    

    Then you can do:

    let encoder = JSONEncoder()
    encoder.keyEncodingStrategy = .convertToSnakeCase
    
    let imageUrl = URL(string: "https://www.sticky.digital/wp-content/uploads/2013/11/img-6.jpg")!
    let ximilarRequest = XimilarRequest(
        taskId: "c03c288b-a249-4b17-9f63-974c2f30beb9",
        version: 2,
        descriptor: 0,
        records: [XimilarRecord(url: imageUrl)]
    )
    
    request.httpBody = try encoder.encode(ximilarRequest)
    
    Login or Signup to reply.
  2. Hi here is the example that should work for you (fill the Auth token and _url of the image):

    import Foundation
    
    let headers = [   "Content-Type": "application/json",   "authorization": "Token __API_TOKEN__" ] let parameters = [   "task_id": "0a8c8186-aee8-47c8-9eaf-348103feb14d",   "version": 2,   "records": [["_url": "__IMAGE URL HERE__"]] ] as [String : Any]
    
    let postData = JSONSerialization.data(withJSONObject: parameters, options: [])
    
    let request = NSMutableURLRequest(url: NSURL(string: "https://api.ximilar.com/recognition/v2/classify")! as URL,
                                            cachePolicy: .useProtocolCachePolicy,
                                        timeoutInterval: 10.0) request.httpMethod = "POST" request.allHTTPHeaderFields = headers request.httpBody = postData as Data
    
    let session = URLSession.shared let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in   if (error != nil) {
        print(error)   } else {
        let httpResponse = response as? HTTPURLResponse
        print(httpResponse)   } })
    
    dataTask.resume()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search