Skip to content

Claude Code Prompts

100 companion flashcards · AI-assisted study content · Open the deck →

This deck is a hands-on guide to getting the most out of Claude Code, the AI-powered coding assistant that works directly in your terminal. The cards walk you through the basics of starting a session, giving Claude access to your project, and using its agentic capabilities to read, edit, and refactor code. You'll also find prompt patterns for common tasks like fixing bugs, writing tests, and searching your codebase, along with a collection of useful slash commands such as /help, /clear, /compact, and /cost that help you manage your sessions more effectively.

The deck is well suited for developers who are new to Claude Code and want to build a strong foundation of practical prompts and commands. It's also a great refresher for anyone who has used the tool occasionally but wants to feel more confident crafting precise instructions or remembering what each command does. If you're looking to turn vague requests into clear, effective prompts that produce reliable results, these flashcards will point you in the right direction.

Because the material is very practical, you'll get the most out of studying by pairing each card with a quick try-it session in your own project. After reviewing a prompt or command, open a terminal and actually run it so the pattern sticks. Spacing your review over a few days rather than cramming will also help, since prompt phrasing is a skill that improves with repeated, spaced practice. Keep a small scratch project handy, and treat the deck as a reference you can return to whenever you need a reminder.

Getting Started with Claude Code

Claude Code is Anthropic's official AI-powered command-line tool designed to help developers write, edit, debug, and understand code directly from the terminal. To begin, you simply run `claude` from any project directory, which launches an interactive session with the assistant. The tool's most powerful feature is its agentic mode, in which Claude can read files, write code, run tests, and execute shell commands autonomously, allowing it to complete complex multi-step tasks end-to-end without constant human direction. Because the working directory provides automatic context, navigating to your project root before starting Claude ensures it has visibility into all files in that directory.

Inside the session, several slash commands help you manage the conversation and inspect state. Running `/help` displays available commands, keyboard shortcuts, and usage information, while `/clear` resets the conversation context entirely, starting a fresh session. The `/compact` command compresses conversation history to save context space while preserving essential information, and `/cost` shows token usage and the estimated API cost for the current session. For developers who prefer modal editing, `/vim` enables Vim keybindings for the input field. If you need to halt a task in progress, pressing `Escape` or `Ctrl+C` interrupts the current operation and returns you to the prompt.

When you want Claude to execute a shell command, a safe pattern is to ask it to report first and explain any failures before acting: "Run [command] and tell me the output. If there are any errors, explain what went wrong before attempting a fix." This keeps you in the loop while still benefiting from Claude's ability to interpret results.

Project Context and Configuration

Beyond the working directory, the most effective way to give Claude Code persistent project knowledge is through a `CLAUDE.md` file placed in the project root. Claude Code automatically reads this markdown file at the start of every session, so it should contain a project overview, the tech stack, coding conventions, common commands, environment setup instructions, and any behavioral preferences you want the assistant to follow. A well-crafted `CLAUDE.md` reduces the need to repeat the same context in every prompt and helps the assistant stay consistent with the rest of your team. You can also use the file to set persistent exclusions, which is a clean alternative to reminding Claude on every request not to touch a particular path.

When joining a new project, you can prompt Claude to explore the structure and produce a high-level overview: "Explore the project structure and give me an overview of the architecture, key files, and how the main features work." For local setup, a prompt like "Read the project structure and tell me exactly what commands I need to run to set up this project locally from scratch" yields a precise, step-by-step answer. To make configuration reproducible across contributors, ask Claude to "Create `.env.example` / config files for this project with all required environment variables documented with descriptions and examples."

You can also ask Claude to explain any third-party package it encounters: "Explain what [library/package] does, why it's used in this project, and what would need to change if we removed it." If you need Claude to leave certain files alone during a particular task, instruct it inline with "Do not modify [filename]. Only change [other file]," or codify the exclusion in `CLAUDE.md` so the rule persists across sessions.

Reading, Searching, and Understanding Code

Before changing anything, it often pays to ask Claude to read the existing code. A simple "Read [filename] and explain what it does" or just "Read [filename]" gets Claude oriented, after which you can drill in with follow-up questions. For specific functions, the prompt "Read [file:line_number] and explain what this function does, including its inputs, outputs, and side effects" produces a focused explanation. To find where a symbol or pattern is used, ask "Find all places where [function/variable/pattern] is used" or "Search for files containing [keyword]."

When the codebase is unfamiliar, prompts that invite summarization are especially effective. "Explain the design patterns used in this codebase, why they were chosen, and how they interact with each other" turns Claude into a tutor. You can also test its understanding with "In your own words, explain how [feature/system] works based on the code. Then identify any gaps or potential issues." When chasing a bug, "Walk me through how data flows from [input] to [output] in this code, and identify where [bug symptom] could originate" is a powerful way to surface the root cause without randomly editing files.

For error messages, the best practice is to paste the full text directly into the prompt: "I'm getting this error: [paste error]. What does it mean and how do I fix it?" This gives Claude everything it needs to interpret the message and suggest concrete next steps. The same principle of providing full context applies whether the error is from a tool, a test runner, or a runtime exception.

Writing, Editing, and Refactoring Code

When you want Claude to change existing code, specificity is the most important ingredient. To refactor, state the goal explicitly: "Refactor this function to use async/await instead of callbacks" or "Extract this logic into a separate helper function." To direct the assistant toward consistency with the rest of the project, anchor it to a reference: "Match the coding style used in [filename]" or "Follow the same patterns as the existing [controllers/services/models]." For language-specific polish, "Rewrite this in idiomatic [Python/Go/TypeScript] following language best practices and community conventions" pushes Claude away from generic, translated code. For tangled logic, ask "This function is too complex. Break it into smaller, single-responsibility functions, keeping the public interface the same."

For bug fixes, the most effective prompts describe the symptom and the expected behavior: "This function returns null when the user has no orders, but it should return an empty array instead." To add a new feature, give Claude enough context to make good decisions: "Add a [feature] to [component] that [behavior]. It should work like [example] and follow the existing patterns in [reference file]." When creating a new file, the prompt "Create [filename] with [specific content/structure]. It should [behavior/purpose] and follow the conventions in [reference file]" produces output that fits the surrounding code. For boilerplate, the same shape applies: "Generate a [component/class/module] boilerplate for [purpose] following the same structure as [existing example file]." Specialized transformations each have canonical prompts, such as "Convert this synchronous [function/module] to async/await, handling errors properly and preserving all existing behavior" and "Add TypeScript types / type hints to [file], ensuring all function signatures, return types, and variable declarations are typed."

For larger or higher-risk refactors, control the workflow by asking Claude to plan before acting: "Before making any changes, explain exactly what you plan to do and why, then wait for my confirmation." For especially ambitious work, use "First read [files], then plan the refactor, explain the approach, and only start changing code after I approve the plan." You can also invite a dialogue with "Before writing any code, ask me the questions you need answered to implement [feature] correctly," or have Claude surface its reasoning up front with "Before implementing, explain your approach, the key decisions you'll make, and any alternatives you considered." Other useful patterns include "Implement [feature] defensively: validate all inputs at boundaries, handle all error cases explicitly, and never trust external data," "Suggest more descriptive names for these variables: [list]. The names should clearly express intent without abbreviation," and "Write a regex that matches [pattern description] and test it against these examples: [valid examples] vs [invalid examples]." For version control hiccups, "I have a merge conflict in [file]. Read the conflict markers and resolve it by [keeping feature/applying both changes/choosing the correct version]" gives Claude the context it needs to make the right call. Smaller design questions, such as choosing a data structure, fit the same pattern: "I need to store [data type] with [operations needed]. What data structure would be most efficient and why?" Finally, for new standalone programs, "Create a CLI tool in [language] that [behavior]. It should accept [flags/arguments] and output [format]" produces a working starting point.

Testing, Debugging, and Code Review

Claude Code is a capable test author when given clear scope. A good starting prompt is "Write unit tests for [function/file] covering edge cases including null inputs, empty arrays, and boundary values." For more advanced coverage, ask for "test fixtures for [model/feature] that cover: a typical case, an edge case with empty values, and a case with maximum data," or for end-to-end assurance, "Write integration tests for [feature] that test the full request/response cycle including database interactions and edge cases." If you want to harden an existing module, "Analyze [file/module] and identify untested code paths. Write tests for the most critical gaps, prioritizing error handling and edge cases" produces a focused improvement plan.

When a test is failing, hand Claude the full error and ask it to find the cause rather than guess at a fix: "This test is failing with [error message]. Read the test and the code it tests, then find and fix the root cause." For reviews, the prompt "Review [file] for code quality, potential bugs, readability issues, and adherence to best practices. Suggest specific improvements" is a strong general-purpose template, and you can apply the same shape to pull requests with "Review the changes in [files] as if doing a code review: check for bugs, security issues, missing tests, and adherence to the project's coding standards."

Specialized reviews benefit from explicit scope. For security, ask "Review [file or feature] for security vulnerabilities including XSS, SQL injection, and OWASP top 10 issues," or build security into a feature from the start with "Implement [feature] with security as the top priority. Validate all inputs, sanitize outputs, and explain any security decisions made." For performance, "Identify performance bottlenecks in [file/function] and suggest optimizations, focusing on [N+1 queries / memory usage / response time]" targets the analysis to your concern. When you are weighing options, the prompt "What are the tradeoffs between [approach A] and [approach B] for [use case]? Which would you recommend and why?" is a good way to get an opinionated answer with reasoning.

APIs, Data, and Infrastructure

Claude Code can scaffold and modify the moving parts of a typical web application. For new endpoints, a complete prompt looks like "Create a [GET/POST/PUT/DELETE] endpoint at [path] that [behavior]. It should validate [inputs] and return [response format]," and the same shape extends to OpenAPI documentation: "Generate OpenAPI/Swagger documentation for the [endpoint or file], including request/response schemas and example payloads." For GraphQL services, "Generate GraphQL schema types for [entities] with queries for [list/find], mutations for [create/update/delete], and proper resolver hints" produces a coherent starting point. For real-world usage, prompts like "Add cursor-based pagination to the [endpoint] returning [per_page] items per page with a next_cursor for subsequent requests" and "Add filtering and sorting to [endpoint] so users can filter by [fields], sort by [columns], and paginate results with [limit/offset or cursor]" give Claude the parameters it needs. To make endpoints robust, use "Add input validation to [endpoint/form] ensuring [field constraints]. Return descriptive validation errors for each invalid field." Rate limiting, caching, and resilience each have natural prompt patterns: "Add rate limiting to [endpoint] allowing [N] requests per [time window] per [user/IP], returning a 429 with retry-after header when exceeded"; "Add caching to [function/endpoint] with a [N minute] TTL, using [Redis/in-memory/HTTP cache headers] and cache invalidation for [events]"; and "Add exponential backoff retry logic to [API call/operation] with [max N retries], jitter, and logging of each attempt."

For data work, prompts should describe the desired outcome in concrete terms. Database work begins with a design prompt: "Design a normalized database schema for [feature/application] with tables, columns, data types, constraints, and foreign key relationships," and changes use the template "Create a migration to [add/modify/remove] [column/table] with [data type and constraints] following the existing migration conventions." Soft deletes, queries, and seed data all have canonical prompts: "Add soft delete functionality to [model] so records are marked deleted_at rather than removed, and all queries exclude soft-deleted records"; "Write a SQL query that [returns/aggregates/joins] [data description], optimized for [read performance / correctness / clarity]"; "Create a seeder for [model] with [N] realistic sample records covering [edge cases / varied scenarios]"; and "Generate [N] realistic mock records for [entity] in [JSON/SQL/CSV] format, varying the fields to cover different scenarios." Slow queries benefit from "This query is slow: [paste query]. Analyze it and rewrite it to be more efficient. Suggest any indexes that should be added."

Beyond the request layer, Claude can wire up jobs, uploads, auth, observability, and deployment. Useful prompts include "Create a background job that [behavior] triggered by [event], with retry logic, error handling, and progress logging"; "Add file upload support for [endpoint] accepting [file types] up to [size], storing in [S3/local disk], and validating file contents"; "Implement [JWT/session/OAuth] authentication for [framework], including login, logout, token refresh, and protected route middleware"; "Create a webhook handler for [service] that validates the signature, processes [event types], and responds within 5 seconds"; and "Create a data pipeline that [reads from source], [transforms data], and [writes to destination], handling errors and partial failures." For observability, "Add metrics, tracing, and structured logging to [service/endpoint] so we can monitor request rates, latency, and error rates" and "Define alerting rules for [service] that trigger when [error rate / latency / queue depth] exceeds [threshold] for [duration]" cover the major practices, and "Add structured logging to [file/function] that logs [events] with appropriate log levels (debug/info/warn/error)" handles the logging details. For delivery, the prompt "Create a [GitHub Actions / GitLab CI] workflow that runs [tests/builds/deploys] on [trigger events] for this [framework] project" produces a working starter workflow, while "Create a Dockerfile for this [language/framework] app that is optimized for production with a multi-stage build" handles containerization. A health check is one line: "Add a /health endpoint that checks [database connectivity / external service availability / disk space] and returns status 200 OK or 503 with details."

Architecture, Documentation, and Release Workflow

For higher-level work, the prompts shift from individual files to systems. To evaluate an existing design, ask "Review the current architecture of [system/feature] and identify any design issues, scalability concerns, or improvements to consider," or "Identify the top 5 pieces of technical debt in [file/module] ranked by impact and effort, and suggest a remediation plan for each." When extracting responsibilities, "Extract [logic] from [controller/class] into a dedicated service class, following the single responsibility principle and dependency injection pattern" is a clean, repeatable pattern. For larger extractions, "Identify bounded contexts in this codebase and propose how to extract [module] into an independently deployable service with a clear API boundary" frames the migration as a design problem.

For new systems, the design-doc prompt is a useful forcing function: "Write a technical design document for [feature] covering: requirements, proposed solution, alternative approaches, risks, and success metrics." State machines and event-driven designs have dedicated templates: "Implement a state machine for [entity] with states [list] and transitions [list], enforcing valid transitions and logging state changes" and "Refactor [feature] to use event sourcing: store domain events, rebuild state from events, and add event projections for queries." For search features, "Add full-text search to [model/endpoint] that searches [fields], ranks results by relevance, and supports [filters/pagination]" and "Add autocomplete to [search field] that queries [endpoint] on keypress with [debounce ms] delay, displaying top [N] results" are complete starting points. Feature flags are similarly straightforward: "Add a feature flag for [feature] using [library/config], defaulting to disabled, so it can be enabled per user/environment." Frontend quality has its own canonical prompt: "Ensure [component/page] meets WCAG 2.1 AA standards: proper ARIA labels, keyboard navigation, color contrast, and screen reader support." A small but useful UX prompt is "Improve the error messages in [file] to be more descriptive, actionable, and user-friendly."

Documentation and release tasks round out the workflow. To produce a README, ask "Generate a README for this project including: overview, features, prerequisites, installation steps, usage examples, and contributing guide." For ongoing maintenance, "Based on the changes in [files], generate a changelog entry in [Keep a Changelog / conventional format] for version [X.X.X]" and "I need to upgrade [package] from [version A] to [version B]. Read the changelog and migrate any breaking API changes in this codebase" cover the common cases. Before shipping, "Generate a pre-deployment checklist for this project covering: environment variables, database migrations, cache warming, and health checks" produces a concrete list. For the kind of small polish that is easy to forget, prompts like "Add documentation to [file] explaining the purpose of each function, its parameters, return values, and any important behavior" and "Suggest more descriptive names for these variables: [list]. The names should clearly express intent without abbreviation" keep the codebase pleasant to work in over time.

Frequently asked questions

What is Claude Code?

Claude Code is Anthropic's official AI-powered CLI tool that helps developers write, edit, debug, and understand code directly in the terminal.

What is the /compact command?

`/compact` compresses the conversation history to save context space while preserving the essential information.

How do you ask Claude Code to optimize performance?

"Identify performance bottlenecks in [file/function] and suggest optimizations, focusing on [N+1 queries / memory usage / response time]."

How do you get Claude Code to document code?

"Add documentation to [file] explaining the purpose of each function, its parameters, return values, and any important behavior."

How do you use Claude Code to write a regex?

"Write a regex that matches [pattern description] and test it against these examples: [valid examples] vs [invalid examples]."

How do you ask Claude Code to add type safety?

"Add TypeScript types / type hints to [file], ensuring all function signatures, return types, and variable declarations are typed."

How do you ask Claude to handle authentication?

"Implement [JWT/session/OAuth] authentication for [framework], including login, logout, token refresh, and protected route middleware."

How do you ask Claude to generate mock data?

"Generate [N] realistic mock records for [entity] in [JSON/SQL/CSV] format, varying the fields to cover different scenarios."

How do you ask Claude Code to add validation?

"Add input validation to [endpoint/form] ensuring [field constraints]. Return descriptive validation errors for each invalid field."

What is the best prompt for extracting a service?

"Extract [logic] from [controller/class] into a dedicated service class, following the single responsibility principle and dependency injection pattern."

Drill this topic

100 flashcards on Claude Code Prompts — free, no signup needed to start.

Study Claude Code Prompts flashcards

LearnWiki pages are generated with AI assistance from LearnCoachAssist's reviewed study catalog and may contain errors — verify anything critical against your course materials.