---
title: "Call a chat completion API with curl and Go"
slug: "chat-completion"
description: "Send one chat completion request with curl and with Go, read the reply and the token count, and see what a missing API key looks like."
published: "2026-12-03"
updated: "2026-12-03"
canonical: "https://aifree.dev/courses/learn-llm/chat-completion"
---

# Call a chat completion API with curl and Go

How do you send a question to a language model from code and read its answer?

## Run it against a real free API

The outputs in this lesson are simulated by a local mock server. To get real answers, create a free key at Mistral AI Free Plan and set these variables. Never put the key in your code.

```sh
export LLM_BASE_URL=https://api.mistral.ai/v1
export LLM_MODEL=mistral-large-4
export LLM_API_KEY=your-key
```

[Mistral AI Free Plan: what is free and how to get a key](https://aifree.dev/offer/mistral-ai-free-plan)

## Predict

A chat completion request goes out and a JSON response comes back. Where is the model's reply text?

- In a top-level field called text
- In choices[0].message.content
- In the usage object

Answer: In choices[0].message.content — The response holds a list of choices; the first one has a message, and the message has the content.

Next you send the request and find the reply yourself.

## The request

A chat API is one HTTP endpoint. You `POST` JSON to `<base URL>/chat/completions` with a `model` id and a list of `messages`, each with a `role` and `content`. Three environment variables carry what changes between providers: `LLM_BASE_URL`, `LLM_MODEL` and `LLM_API_KEY`. The key travels in the `Authorization: Bearer` header. Keep it out of your code, so you never commit it by accident.

## Ask a question with curl

```sh
curl -s "$LLM_BASE_URL/chat/completions" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $LLM_API_KEY" \
  -d '{
    "model": "'"$LLM_MODEL"'",
    "messages": [{"role": "user", "content": "What is the capital of France?"}]
  }'
```

Output:

```
{
  "id": "chatcmpl-mock-0001",
  "object": "chat.completion",
  "created": 1796256000,
  "model": "mock-chat-1",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "The capital of France is Paris."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 6,
    "completion_tokens": 6,
    "total_tokens": 12
  }
}
```

_Simulated response (local mock server), 2026-12-03._

This is the simulated output. A real model returns a longer, different text and its own ids.

## The response

The answer is JSON. `choices` is a list; each choice has a `message` with the reply in `content`, and a `finish_reason`: `stop` means the model finished by itself, `length` means it hit the token limit. `usage` counts the tokens of your prompt and of the reply. Providers bill by those tokens and apply rate limits to them, so it is worth reading them.

## The same call in Go

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
)

func main() {
	payload, _ := json.Marshal(map[string]any{
		"model": os.Getenv("LLM_MODEL"),
		"messages": []map[string]string{
			{"role": "user", "content": "What is the capital of France?"},
		},
	})
	req, _ := http.NewRequest("POST", os.Getenv("LLM_BASE_URL")+"/chat/completions", bytes.NewReader(payload))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+os.Getenv("LLM_API_KEY"))

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	defer res.Body.Close()

	var out struct {
		Choices []struct {
			Message struct {
				Content string `json:"content"`
			} `json:"message"`
		} `json:"choices"`
		Usage struct {
			TotalTokens int `json:"total_tokens"`
		} `json:"usage"`
	}
	if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	fmt.Println(out.Choices[0].Message.Content)
	fmt.Println("total tokens:", out.Usage.TotalTokens)
}
```

Output:

```
The capital of France is Paris.
total tokens: 12
```

_Simulated response (local mock server), 2026-12-03._

Go's standard library is enough: net/http sends the request and encoding/json reads the reply.

## Fix it

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
)

func main() {
	payload, _ := json.Marshal(map[string]any{
		"model": os.Getenv("LLM_MODEL"),
		"messages": []map[string]string{
			{"role": "user", "content": "What is the capital of France?"},
		},
	})
	req, _ := http.NewRequest("POST", os.Getenv("LLM_BASE_URL")+"/chat/completions", bytes.NewReader(payload))
	req.Header.Set("Content-Type", "application/json")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	defer res.Body.Close()
	if res.StatusCode != http.StatusOK {
		fmt.Fprintln(os.Stderr, "request failed:", res.Status)
		os.Exit(1)
	}

	var out struct {
		Choices []struct {
			Message struct {
				Content string `json:"content"`
			} `json:"message"`
		} `json:"choices"`
	}
	json.NewDecoder(res.Body).Decode(&out)
	fmt.Println(out.Choices[0].Message.Content)
}
```

The program exits with an error instead of printing the reply. What is wrong?

- The request has no Authorization header
- The model id is too long
- The JSON body is invalid

Answer: The request has no Authorization header — The server cannot tell who is calling, so it answers 401 Unauthorized.

Error message:

```
request failed: 401 Unauthorized
```

Fixed:

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
)

func main() {
	payload, _ := json.Marshal(map[string]any{
		"model": os.Getenv("LLM_MODEL"),
		"messages": []map[string]string{
			{"role": "user", "content": "What is the capital of France?"},
		},
	})
	req, _ := http.NewRequest("POST", os.Getenv("LLM_BASE_URL")+"/chat/completions", bytes.NewReader(payload))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+os.Getenv("LLM_API_KEY"))

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	defer res.Body.Close()
	if res.StatusCode != http.StatusOK {
		fmt.Fprintln(os.Stderr, "request failed:", res.Status)
		os.Exit(1)
	}

	var out struct {
		Choices []struct {
			Message struct {
				Content string `json:"content"`
			} `json:"message"`
		} `json:"choices"`
	}
	json.NewDecoder(res.Body).Decode(&out)
	fmt.Println(out.Choices[0].Message.Content)
}
```

Output:

```
The capital of France is Paris.
```

_Simulated response (local mock server), 2026-12-03._

## Say it back

In your own words: what goes into a chat completion request, what comes back, and where does the key belong?

Our sentence: I POST a model id and a list of messages to the chat completions endpoint, with my key in the Authorization header. I get back choices, and the reply is in the first choice's message content, plus a usage count of tokens. The key stays in an environment variable, never in the code.

## Mission (10 min)

Get a free API key from the offer linked at the top of this lesson, set the three variables, then run both programs from this lesson against it. Change the question and see how the reply and the token count change.

```sh
export LLM_BASE_URL=<base URL from the offer page>
export LLM_MODEL=<model id from the offer page>
export LLM_API_KEY=<your key>
curl -s "$LLM_BASE_URL/chat/completions" ...
go run main.go
```

## Common questions

### What is a chat completion API?

It is an HTTP endpoint where you send a conversation as a list of messages and the model returns the next message. The format started with OpenAI and many providers copy it, which is why one program can talk to several of them by changing only the base URL, the model id and the key. The request carries the whole conversation each time.

### Why do the examples read the base URL and model from environment variables?

The URL, the model id and the key differ for every provider, and they change over time as models are retired. Reading them from the environment keeps that out of the code, so the same program runs against a local test server or a real provider. It also keeps the key out of your repository, where it could leak.

### Are the outputs in this lesson from a real model?

No. They come from a small local mock server in this site's repository that follows the same request and response format, so the programs can be checked without a key or a network. Real answers will differ in wording and ids. The box at the top of the lesson shows how to point the same programs at a real free API.

## Sources

- https://platform.openai.com/docs/api-reference/chat/create (read 2026-12-03)
- https://docs.mistral.ai/capabilities/completion/ (read 2026-12-03)
- https://pkg.go.dev/net/http (read 2026-12-03)
- https://pkg.go.dev/encoding/json (read 2026-12-03)

Simulated responses from a local mock server, not from a real model. Run with local mock server (scripts/course-llm-mock.ts), go1.27.4 darwin/arm64, curl on 2026-12-03.
