# Flask + Anthropic Python SDK: non-streaming message endpoint

1. Install the SDK: `pip install anthropic`. Use the sync `Anthropic()` client in Flask views. Flask view functions run synchronously, so the sync client is the natural fit; the async client buys you nothing in a plain sync view.
2. Load the API key from your server config or environment into the client constructor. Keep it server-side. A Flask view is server code, which is exactly where the key belongs.
3. Build the request the same way as any Messages API call:

```
{
  "model": "claude-sonnet-5",
  "max_tokens": 1024,
  "system": "You answer concisely.",
  "messages": [{"role": "user", "content": "Explain idempotency keys."}]
}
```

4. `system` is a top-level parameter, not a message role. The Messages API reference defines it at the top level.
5. Extract the text from `message.content` (list of content blocks) and check `message.stop_reason` before returning JSON to the caller.
6. The SDK has built-in retries for transient failures (documented in the client-SDK overview), but a malformed request is your bug, not a retry candidate. Log the error type and message, fix the payload, and do not hammer the API.

Failure modes this prevents: awaiting a coroutine that never runs in a sync view; retrying malformed requests in a loop; reading the answer from the wrong field and returning an empty string.
