Overview
Thequery() function is the simplest way to interact with Claude Code. It’s perfect for one-shot questions, batch processing, and scenarios where you know all your inputs upfront.
For interactive conversations with back-and-forth messaging, use ClaudeSDKClient instead.
When to Use query()
Usequery() when you need:
- Simple one-off questions - “What is 2+2?”
- Batch processing - Processing multiple independent prompts
- Code generation - Creating files or analyzing code
- Automation scripts - CI/CD pipelines, automated tasks
- Fire-and-forget - When all inputs are known upfront
Basic Example
Here’s the simplest way to usequery():
Working with Message Types
Thequery() function yields different message types. Here’s how to handle them:
Using Options
Customize Claude’s behavior withClaudeAgentOptions:
Permission Modes
Control how Claude handles potentially dangerous operations:Complete Example
Here’s a practical example that creates a file and handles all message types:Streaming Mode
For advanced use cases, you can stream multiple prompts:Best Practices
Handle All Message Types
Handle All Message Types
Always handle
AssistantMessage, UserMessage, SystemMessage, and ResultMessage types to capture the full conversation flow.Set Appropriate Permissions
Set Appropriate Permissions
Use the most restrictive permission mode that works for your use case. Start with
default and only escalate if needed.Specify Working Directory
Specify Working Directory
When working with files, always set
cwd in options to ensure Claude operates in the correct directory.Limit Tool Access
Limit Tool Access
Use
allowed_tools to restrict which tools Claude can use, improving security and reducing unexpected behavior.Add System Prompts
Add System Prompts
Provide clear context through
system_prompt to guide Claude’s responses and improve result quality.Next Steps
Interactive Conversations
Learn how to use ClaudeSDKClient for bidirectional conversations
Custom Tools
Create custom tools to extend Claude’s capabilities
Configuration Options
Explore all available ClaudeAgentOptions
Message Types
Deep dive into message types and content blocks