0
# Simple Queries
1
2
The `query()` function provides unidirectional query interface for one-shot interactions with Claude Code. This is ideal for simple, stateless queries where you don't need bidirectional communication or conversation management.
3
4
## Capabilities
5
6
### Main Query Function
7
8
Sends a prompt to Claude Code and returns an async iterator of response messages. Supports both string prompts for simple queries and async iterables for streaming mode.
9
10
```python { .api }
11
async def query(
12
*,
13
prompt: str | AsyncIterable[dict[str, Any]],
14
options: ClaudeCodeOptions | None = None,
15
transport: Transport | None = None,
16
) -> AsyncIterator[Message]:
17
"""
18
Query Claude Code for one-shot or unidirectional streaming interactions.
19
20
Args:
21
prompt: The prompt to send to Claude. Can be a string for single-shot queries
22
or an AsyncIterable[dict] for streaming mode with continuous interaction.
23
options: Optional configuration (defaults to ClaudeCodeOptions() if None).
24
transport: Optional transport implementation. If provided, this will be used
25
instead of the default transport selection based on options.
26
27
Yields:
28
Messages from the conversation
29
30
Returns:
31
AsyncIterator[Message]: Stream of messages from Claude
32
"""
33
```
34
35
## Usage Examples
36
37
### Simple String Query
38
39
```python
40
import anyio
41
from claude_code_sdk import query
42
43
async def main():
44
async for message in query(prompt="What is the capital of France?"):
45
print(message)
46
47
anyio.run(main)
48
```
49
50
### Query with Options
51
52
```python
53
from claude_code_sdk import query, ClaudeCodeOptions, AssistantMessage, TextBlock
54
55
async def main():
56
options = ClaudeCodeOptions(
57
system_prompt="You are an expert Python developer",
58
max_turns=1,
59
cwd="/home/user/project"
60
)
61
62
async for message in query(
63
prompt="Create a Python web server",
64
options=options
65
):
66
if isinstance(message, AssistantMessage):
67
for block in message.content:
68
if isinstance(block, TextBlock):
69
print(block.text)
70
71
anyio.run(main)
72
```
73
74
### Tool Usage Query
75
76
```python
77
from claude_code_sdk import query, ClaudeCodeOptions
78
79
async def main():
80
options = ClaudeCodeOptions(
81
allowed_tools=["Read", "Write", "Bash"],
82
permission_mode='acceptEdits' # auto-accept file edits
83
)
84
85
async for message in query(
86
prompt="Create a hello.py file",
87
options=options
88
):
89
# Process tool use and results
90
print(message)
91
92
anyio.run(main)
93
```
94
95
### Streaming Mode Query
96
97
```python
98
from claude_code_sdk import query
99
100
async def main():
101
async def prompts():
102
yield {"type": "user", "message": {"role": "user", "content": "Hello"}}
103
yield {"type": "user", "message": {"role": "user", "content": "How are you?"}}
104
105
# All prompts are sent, then all responses received
106
async for message in query(prompt=prompts()):
107
print(message)
108
109
anyio.run(main)
110
```
111
112
### Custom Transport Query
113
114
```python
115
from claude_code_sdk import query, Transport
116
117
class MyCustomTransport(Transport):
118
# Implement custom transport logic
119
async def connect(self) -> None:
120
pass
121
122
async def write(self, data: str) -> None:
123
pass
124
125
def read_messages(self):
126
# Custom implementation
127
yield {}
128
129
# ... implement other required methods
130
131
async def main():
132
transport = MyCustomTransport()
133
async for message in query(
134
prompt="Hello",
135
transport=transport
136
):
137
print(message)
138
```
139
140
## When to Use query()
141
142
**Ideal for:**
143
- Simple one-off questions ("What is 2+2?")
144
- Batch processing of independent prompts
145
- Code generation or analysis tasks
146
- Automated scripts and CI/CD pipelines
147
- When you know all inputs upfront
148
- Fire-and-forget style operations
149
150
**Not suitable for:**
151
- Interactive conversations with follow-ups
152
- Chat applications or REPL-like interfaces
153
- When you need to send messages based on responses
154
- When you need interrupt capabilities
155
- Long-running sessions with state
156
157
**For interactive use cases, use [ClaudeSDKClient](./interactive-client.md) instead.**
158
159
## Key Differences from ClaudeSDKClient
160
161
- **Unidirectional**: Send all messages upfront, receive all responses
162
- **Stateless**: Each query is independent, no conversation state
163
- **Simple**: Fire-and-forget style, no connection management
164
- **No interrupts**: Cannot interrupt or send follow-up messages
165
- **Limited custom tools**: Cannot use hook system or advanced MCP features
166
167
## Message Handling
168
169
The query function returns an `AsyncIterator[Message]` where `Message` can be:
170
171
- `UserMessage`: User input messages
172
- `AssistantMessage`: Claude's responses with content blocks
173
- `SystemMessage`: System notifications and metadata
174
- `ResultMessage`: Final result with cost and usage information
175
- `StreamEvent`: Streaming updates during partial message processing
176
177
See [Message Types and Content](./message-types.md) for detailed information about message structures.