CertSafari
    Anthropic Claude Certified Developer – Foundations (CCDV-F)· Lessons

    Domain 2 · Lesson 7/25

    Calling Claude from code: JSON requests and sync vs async patterns

    Software Engineering Foundations

    8 min read
    5.52% of exam
    4 sources
    Published 17 Nov 2026
    Docs as of 11 Nov 2026

    What you will be able to do

    • Build a Messages API conversation as JSON and store it in your own storage between requests
    • Choose between a blocking call, an async client, streaming and submit-and-poll for a given workload
    • Explain why a request with a large max_tokens value should stream even when nobody reads the text as it arrives

    Key concept

    Choosing a call pattern by who is waiting — Your code can wait for Claude in four ways: block, await an async client, read a stream, or submit work and collect it later. Pick one by asking who is waiting for the answer and how long the response takes to produce.

    1.The Messages API as a JSON-over-HTTP endpoint

    Every Claude integration ends up as a JSON body sent to the /v1/messages endpoint, with a JSON message coming back, whichever SDK wraps the call. The body names a model, sets a max_tokens ceiling and carries a messages array. Each entry in that array is an object with a role and content. Content is either a plain string or an array of typed content blocks, and a string is shorthand for a single text block. A system prompt does not go into the array. It goes in the top-level system parameter.

    A multi-turn conversation is just a JSON array of alternating rolesjson
    [
      {"role": "user", "content": "Hello there."},
      {"role": "assistant", "content": "Hi, I'm Claude. How can I help you?"},
      {"role": "user", "content": "Can you explain LLMs in plain English?"},
    ]

    The server keeps nothing between calls (Stateless Messages API (client holds the conversation)), so storing the conversation is your code's job. After each turn, append Claude's reply to the array, serialize it as JSON and save it in your own database under the user's session. On the next request, load the array, add the new user turn and send the whole history again. One request can carry at most 100,000 messages.

    Errors come back as HTTP status codes, and the code tells you whether retrying can help. One example of a request that will never succeed: on a model without prefill support, a request whose last message is a partial assistant turn gets a 400 error. Sending the same body again fails the same way. An overloaded_error is different. It corresponds to HTTP 529 and reports a capacity problem on the server side, not a problem with your request.

    Checkpoint 1 of 3· Fill the gap

    This messages array carries a multi-turn conversation to /v1/messages. Which role belongs on Claude's earlier reply?

    [
      {"role": "user", "content": "Hello there."},
      {"role": " ? ", "content": "Hi, I'm Claude. How can I help you?"},
      {"role": "user", "content": "Can you explain LLMs in plain English?"},
    ]

    Sources12

    2.Blocking calls and the async client

    The simplest pattern is the blocking call. client.messages.create(...) sends the request, and the calling code waits until the complete Message object comes back. Use it as the default in scripts, CLI tools and worker processes that have nothing else to do while they wait. The code runs top to bottom and the result is a single object.

    Blocking becomes a problem when the caller has other work to do, as in a web service built on asyncio where many requests share one event loop. The Python SDK provides AsyncAnthropic for this case. It takes the same parameters, but you await messages.create, so other coroutines keep running while the request is in flight.

    The async client: same request shape, awaited inside an event looppython
    async def main() -> None:
        message = await client.messages.create(
            max_tokens=1024,
            messages=[
                {
                    "role": "user",
                    "content": "Hello, Claude",
                }
            ],
            model="claude-opus-5-5",
        )
        print(message.content)
    
    
    asyncio.run(main())

    For heavier async workloads, the SDK can use aiohttp as its HTTP backend instead of the default. Keep in mind what async does and does not change. It changes how your program waits, not how long Claude takes: await still returns only after the complete message has arrived.

    Checkpoint 2 of 3· Check yourself

    A team's asyncio web service swaps its blocking client.messages.create(...) calls for AsyncAnthropic and awaits messages.create. What does this change?

    Sources3

    3.Streaming and submit-and-poll

    Streaming changes when the response arrives: it comes as a series of events while the model is still generating. The event format is covered in Streaming over server-sent events. Streaming beats a blocking call in two cases. The obvious one is a user watching text appear. The less obvious one is a long generation: with a large max_tokens, the SDK requires streaming, because events keep the HTTP connection alive and a silent connection would hit an HTTP timeout. If you don't need the text as it arrives, stream.get_final_message() collects all the events into the complete Message. The Python SDK supports both sync and async streams.

    Streaming under the hood, one complete Message at the endpython
    with client.messages.stream(
        max_tokens=128000,
        messages=[{"role": "user", "content": "Write a detailed analysis..."}],
        model="claude-opus-5-5",
    ) as stream:
        message = stream.get_final_message()

    Streaming also adds two obligations for your parser. An overloaded_error can arrive in the middle of a stream as an error event instead of as a status code. And new event types may be added over time, so your code has to skip types it doesn't recognise instead of crashing on them.

    Submit-and-poll separates the request from the response completely. You submit the work, your code moves on, and you collect the results later. The standard example is the Message Batches API and realtime vs batch. Batches run within a 24-hour processing window at 50 percent of standard API prices. Because no connection stays open, a batch can also run more iterations in a turn than a synchronous request.

    Four ways to wait for Claude, and when each one wins
    PatternHow the caller waitsChoose it when
    Blocking messages.createThe calling code waits for the complete MessageScripts and workers with nothing else to do
    AsyncAnthropic with awaitThe event loop keeps serving other coroutinesAn async service handles many requests at once
    messages.streamThe connection stays open while events arriveA user watches text appear, or a large max_tokens would risk HTTP timeouts
    Batch (submit-and-poll)No open connection; results are collected laterBulk work that can wait up to 24 hours in return for half the price

    Checkpoint 3 of 3· Check yourself

    Your service reads messages.stream events directly and has to detect when Anthropic's servers are overloaded. Which design handles this correctly?

    Sources24

    Sources

    (4)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “you specify the prior conversational turns with the messages parameter”
      ↩︎ The Messages API as a JSON-over-HTTP endpoint
      “There is a limit of 100,000 messages in a single request.”
      ↩︎ The Messages API as a JSON-over-HTTP endpoint
    2. 2.
      “you might receive an overloaded_error, which would normally correspond to an HTTP 529 in a non-streaming context”
      ↩︎ The Messages API as a JSON-over-HTTP endpoint
      “The Python SDK allows both sync and async streams.”
      ↩︎ Streaming and submit-and-poll
      “your code should handle unknown event types gracefully.”
      ↩︎ Streaming and submit-and-poll
      “This is especially useful for requests with large max_tokens values, where the SDK requires streaming to avoid HTTP timeouts.”
      ↩︎ Key concept
      “This is especially useful for requests with large max_tokens values, where the SDK requires streaming to avoid HTTP timeouts.”
      ↩︎ Exam trap 1
      “returning the complete Message object, identical to what client.messages.create() returns”
      ↩︎ Checkpoint
      “This is especially useful for requests with large max_tokens values, where the SDK requires streaming to avoid HTTP timeouts.”
      ↩︎ Prediction
      “you might receive an overloaded_error, which would normally correspond to an HTTP 529 in a non-streaming context”
      ↩︎ Checkpoint
    3. 3.
      “For improved async performance, you can use the aiohttp HTTP backend instead of the default httpx2”
      ↩︎ Blocking calls and the async client
    4. 4.
      “Because there is no open connection to maintain, the batch loop can run more iterations in a turn than a synchronous request”
      ↩︎ Streaming and submit-and-poll
      “Standard batch pricing (50 percent of standard API prices) applies.”
      ↩︎ Streaming and submit-and-poll

    Continue to part 2 of 2

    Claude Code in the SDLC: CI, automated review and refactoring

    Spotted a mistake, or was something unclear? Tell us.