Reputation: 1176
I am relatively new to networking in Swift, and especially POST requests. I have read the documentation for the Clarifai API and for Alamofire, but haven't quite figured out how to write a working request using Alamofire. So far I have found the following piece of code which creates a structure that conforms to the API of Clarifai which wants the request to be structured like this:
curl -X POST \
-H "Authorization: Key YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d @https://api.clarifai.com/v2/models/aaa03c23b3724a16a56b629203edc62c/outputs << FILEIN
{
"inputs": [
{
"data": {
"image": {
"base64": "$(base64 /home/user/image.png)"
}
}
}
]
}
FILEIN
This is the swift code I found that achieves exactly that:
struct ImageObj: Codable { let base64: String }
struct DataObj: Codable {
let image: ImageObj
}
struct InputObj: Codable {
let data: DataObj
}
struct InputsContainerObj: Codable {
let inputs: [InputObj]
}
let imageObj = ImageObj(base64: "abc123")
let dataObj = DataObj(image: imageObj)
let inputObj = InputObj(data: dataObj)
let inputsContainerObj = InputsContainerObj(inputs: [inputObj])
let encoder = JSONEncoder()
do {
let jsonData = try encoder.encode(inputsContainerObj)
let jsonString = String(data: jsonData, encoding: .utf8)!
print(jsonString) //{"inputs":[{"data":{"image":{"base64":"abc123"}}}]}
} catch _ as NSError {
}
Now I have no idea what I should do after this point. I tried writing an Alamofire request using POST, but got stuck on parameters? and encodables? For parameters I tried something like:
let parameters: Parameters = [
"Authorization: Key":"xxxxxxxxxxxxxxxxxxxxxxxx",
"Content-Type":"application/json"]
But I don't know if it is correct. If anyone could help me out here I would greatly appreciate it! Have a nice day everyone!
Upvotes: 3
Views: 226
Reputation: 608
It looks like you've constructed the jsonString from the object and also the headers (you've called them 'parameters'). You should be able to send via the following:
let headers: [String: AnyObject] = [
"Authorization: Key":"xxxxxxxxxxxxxxxxxxxxxxxx",
"Content-Type":"application/json"
]
Alamofire.request(.POST, "https://api.clarifai.com/v2/inputs", parameters: jsonString, headers: headers, encoding: .JSON)
.responseJSON { request, response, JSON, error in
print(response)
print(JSON)
print(error)
}
I've re-named them as headers to make it more clear above. Please note, I've masked out the Authorization Key (both in the answer and in the original question) - generally you wouldn't want to share this to the public.
Upvotes: 1