skip to Main Content

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


  1. Chosen as BEST ANSWER

    I solved this issue by creating a custom struct for decoding.


  2. As matt said, you are not decoding the data.

    To decode:

    let decodedData = try JSONDecoder().decode(<YOUR_DECODABLE_TYPE>.self, from: data)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search