Troubleshooting of Ollama API
If you have any questions about the Ollama API, you can post them on the Ollama GitHub Repository.
How to Fix "Unauthorized" Error
Error message:
HTTP Error 401
Response: {"error":"Unauthorized"}
Solution
Verify that your API key is correct by testing it with the following curl command:
curl -s -o /dev/null -w "%{http_code}\n" -X POST https://ollama.com/api/chat -H "Authorization: Bearer REPLACE_WITH_YOUR_API_KEY" -H "Content-Type: application/json" -d '{"model":"gpt-oss:120b","messages":[{"role":"user","content":"hi"}],"stream":false}'
Check the returned status code:
- 200 — the API key is valid
- 401 — the API key is invalid or incorrect
How to fix "json: cannot unmarshal object ..."
Error message:
HTTP Error 400: {"error": "json: cannot unmarshal object into Go struct field ChatRequest.messages of type []api.Message"}
Applicable Model:
- gpt-oss:120b
Solution
Root Cause: Incorrect `messages` format. The API expects an array format, but a single object was being sent.
Incorrect Format in PHP: ❌ This is an object
'messages' => ['role' => 'user', 'content' => $message]
Correct Format in PHP: ✅ This is an array containing an object
'messages' => [['role' => 'user', 'content' => $message]]
Explanation: The `messages` parameter must be an array of message objects, not a single message object. Each message object should contain `role` and `content` properties. The extra square brackets `[]` wrap the message object into an array, which matches the API's expected format.
This fix resolves the `"cannot unmarshal object into Go struct field ChatRequest.messages"` error.
Related links
- Forum: ollama