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
The server is reporting an error for
records
: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 supplyversion
anddescriptor
in curl, but not in the Swift example.Thus, you might try:
Alternatively, you might define
Encodable
types as outlined in Encoding and Decoding Custom Types:Then you can do:
Hi here is the example that should work for you (fill the Auth token and _url of the image):