I am trying to get the response from a POST REQUEST. Once I receive my data, I want to find the specific value of the key that I need. The API I am using returns a response in the following format:
{
"id": "STRING",
"object": "STRING",
"created": INT,
"choices": [{
"index": INT,
"message": {
"role": "STRING",
"content": "STRING",
},
"finish_reason": "STRING"
}],
"usage": {
"prompt_tokens": INT,
"completion_tokens": INT,
"total_tokens": INT
}
}
I have tried decoding the JSON data returned from the HTTP request. I used Decodable identifiers but it was not able to decode the data. Here is my code:
let body: [String: Any] = ["model": "gpt-3.5-turbo", "messages": [["role": "user", "content": "hello"]]]
let jsonData = try? JSONSerialization.data(withJSONObject: body)
let url = URL(string: "https://api.openai.com/v1/chat/completions")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer (API_KEY)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
print("Error took place (error.localizedDescription)")
return
}
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print("Response data string:n (dataString)")
}
}
task.resume()
2
Answers
I solved this issue by creating a custom struct for decoding.
As matt said, you are not decoding the data.
To decode: