How to Use AI to Write Code: The Prompt Engineering Guide for Devs
โก Quick Answer
Prompt engineering for coding โ how to use ChatGPT, Claude, and GitHub Copilot to write better code faster, with templates for functions, reviews, debugging, and architecture.
Get more content like this on Telegram!
Daily AI tips, notes & resources โ free
Advertisement
How to Use AI to Write Code: The Prompt Engineering Guide for Devs
Prompt engineering for code means giving an AI model the types, constraints, and context it needs to generate code that runs without modification โ not just a description of what you want.
Here's what changes with it: a vague request for a database query produces four broken versions. The same request with a schema, error cases, and an ORM client attached produces a working Prisma query on the first try.
The gap between developers who get 2x productivity gains from ChatGPT, Claude, or GitHub Copilot and developers who give up in frustration is almost entirely in how they communicate with the model. AI-assisted coding is a skill โ it improves with deliberate practice, same as any other.
This guide gives you the specific prompts and templates for code generation, debugging, code review, architecture, and documentation.
The Three Biggest Mistakes Developers Make When Prompting for Code
Mistake 1: No Type Specification
โ "Write a function to validate user input"
โ
"Write a TypeScript function validateUserInput(input: unknown):
{ valid: boolean; errors: string[] } that validates:
email format, password (min 8 chars, must include number),
and username (3-30 chars, alphanumeric only)"No types means loose, JavaScript-like output. Specify types and the model generates properly typed, more reliable code.
Mistake 2: No Error Handling Specification
โ "Write a function to fetch user data from our API"
โ
"Write an async fetchUser(userId: string) function using axios.
Handle: 404 (return null, don't throw), 401 (throw AuthError),
network failures (throw NetworkError with retry suggestion),
rate limiting (respect Retry-After header).
Include request timeout of 5000ms."Unrequested error handling gets omitted. Ask for it explicitly, case by case, or the model skips it.
Mistake 3: No Codebase Context
โ "Write a database query to get all active users"
โ
"Write a Prisma query to get all active users.
Schema: users table with fields: id (uuid), email (string),
status (enum: ACTIVE | INACTIVE | SUSPENDED), createdAt.
Include: only users where status = ACTIVE and createdAt > 30 days ago.
Order by createdAt DESC. Limit 100.
Use our existing db client pattern: import { db } from '@/lib/db'"Code Generation Prompts
Function Writing Template
Write a [language] function [functionName]([param types]) that:
Primary behavior:
Input validation:
Error handling:
Performance requirements:
Code style:
- TypeScript with strict types
Example usage:
const result = await functionName(exampleInput);
// Expected: [expected output]Real example:
Write a TypeScript async function createShortUrl(
userId: string,
originalUrl: string,
customSlug?: string
): Promise<{ id: string; shortUrl: string; slug: string }> that:
Primary behavior:
- Validates originalUrl is a valid URL (throw ValidationError if not)
- If customSlug provided: check it's not taken (case-insensitive),
throw SlugTakenError if taken
- If no customSlug: generate a random 6-char alphanumeric slug
- Insert into short_urls table
- Return the created record
Error handling:
- Invalid URL โ throw new ValidationError('Invalid URL format')
- Slug taken โ throw new SlugTakenError('This slug is already in use')
- DB error โ throw new DatabaseError with the original error as cause
Using: Prisma with our db client from '@/lib/db'
Use crypto.randomBytes for slug generation (not Math.random)Class/Component Generation
Create a [React/Vue/etc] component [ComponentName] that:
Props interface:
Behavior:
Styling:
Performance:
Do NOT:
- Use class components
- Import unused dependencies
- Use inline styles except where necessaryAPI Endpoint Template
Write a [Next.js/Express/FastAPI] API endpoint for [route]:
Method: [GET/POST/PUT/DELETE]
Path: [/api/resource/:id]
Request:
- Auth: [required/optional, type: JWT/session]
- Body: [schema if POST/PUT]
- Query params: [if GET]
Response:
- Success: [status code] + [response schema]
- Not found: 404 + { error: "..." }
- Unauthorized: 401 + { error: "..." }
- Validation error: 422 + { errors: [...] }
Middleware to apply:
Database: Using [ORM] with [database]Debugging Prompts
Root Cause Analysis Template
Debug this [language] code. Walk through it step by step.
The code:
[paste code]
The error:
[paste full error message and stack trace]
Expected behavior: [what should happen]
Actual behavior: [what actually happens]
What I've already tried:
Environment: [Node version, framework version, OS if relevant]
Instructions:
1. Trace through the code execution line by line
2. Identify where actual behavior diverges from expected
3. Explain the root cause (not just the symptom)
4. Provide the fix
5. Explain why the fix worksIntermittent Bug Template
I have an intermittent bug that's hard to reproduce.
Symptoms: [describe the bug]
Frequency: [how often it happens]
Conditions when it appears: [specific circumstances]
Conditions when it doesn't appear: [what makes it work correctly]
Relevant code:
[paste code]
Suspected causes I've considered:
What are the possible root causes for this type of intermittent behavior?
Rank them by likelihood given my description.
For the top 2-3 causes, describe how I can add logging to confirm which one it is.Performance Debugging
This code is slow. Profile it analytically.
Code:
[paste code]
Performance data:
- Current execution time: [Xms or Xs]
- Input size when it becomes slow: [N items, MB data, etc.]
- Target execution time: [Yms]
Analyze:
1. What is the algorithmic complexity (Big O) of this code?
2. What are the most expensive operations?
3. What would be the performance at 10x, 100x current input size?
4. What are the highest-leverage optimizations (80/20 rule)?
5. Provide optimized version with explanation of changesCode Review Prompts
Security Review
Review this code for security vulnerabilities.
For each vulnerability found:
- Severity: Critical / High / Medium / Low
- Type: [SQL injection / XSS / IDOR / etc.]
- Specific location in code (line number or code snippet)
- Explanation of the attack vector
- Secure fix with corrected code
Code being reviewed:
[paste code]
Context:
- This code handles: [user inputs / payments / authentication / etc.]
- User trust level: [authenticated users / anonymous / admin only]
- Data sensitivity: [PII / financial / general]Architecture Review
Review the architecture of this system.
[Describe or paste architecture / code structure]
Evaluate:
1. Scalability: Where will this break under 10x current load?
2. Single points of failure: What breaks if one component goes down?
3. Security boundaries: Where are potential unauthorized access points?
4. Maintainability: What will be hardest to change as requirements evolve?
5. Technical debt: What shortcuts will compound into major problems?
For each issue: describe the problem, the risk level, and a solution approach.
Don't soften the criticism โ I need to know the real risks.Documentation Prompts
Auto-Documentation
Write documentation for this [function/API/module]:
[paste code]
Include:
- Purpose: What does this do and why does it exist?
- Parameters: Name, type, description, required/optional, constraints
- Return value: Type and what it represents
- Errors thrown: When and why each error occurs
- Example: One realistic usage example with input and output
- Notes: Any non-obvious behavior, gotchas, or important limitations
Format: [JSDoc / TypeDoc / Google docstring / Markdown]
Audience: [Mid-level developers new to this codebase]For more on AI-assisted development techniques, see our guide on building a full-stack app with AI tools. For the broader prompt engineering foundation, see the complete prompt engineering guide.
Further Reading
- Prompt Engineering for Business: Templates That Get Results
- The Complete Prompt Engineering Guide for 2025 (With 100 Examples)
- Chain of Thought Prompting: The Technique That Makes AI 10x Smarter
- How I Made $2,000 Last Month Just Selling AI Prompts on PromptBase
- The Art of Asking AI the Right Questions (And Getting Real Answers)
- I Spent 100 Hours with ChatGPT-4o โ Here's Everything I Learned
- 10 ChatGPT Prompts That Write Better Emails Than You
- How to Use ChatGPT for Market Research (Step-by-Step Guide)
Advertisement
๐ฌ DiscussionPowered by GitHub Discussions
Frequently Asked Questions

Software Testing Expert & Prompt Engineering
Ensures every release is bug-free through rigorous testing, and crafts high-precision prompts that power our AI-driven workflows. Abdullah Al Arman Emon leads QA and prompt engineering across AiTechWorlds.
Not sure yet? Ask AI about this article
Get an instant, unbiased AI summary of โHow to Use AI to Write Code: The Prompt Engineering Guide for Devsโ.
Advertisement
Related Articles
Jailbreak or Not? Understanding the Ethics of Prompt Manipulation
AI prompt ethics explained โ the real difference between jailbreaking, clever prompting, and legitimate use, plus why AI safety guardrails exist and when to respect them.
How to Build a Prompt Library That Saves You 5 Hours a Week
Build an AI prompt library that saves hours every week โ the exact structure, tagging system, and workflow for organizing prompts you'll actually use and find again.
Prompt Engineering for Business: Templates That Get Results
Business prompt templates that get results โ ready-to-use AI prompts for marketing, HR, strategy, finance, and operations that professionals use to save hours every week.
Chain of Thought Prompting: The Technique That Makes AI 10x Smarter
Chain of thought prompting explained โ how this simple technique transforms AI reasoning, with real examples for math, logic, analysis, and complex decisions.