Follow AiTechWorlds on LinkedIn for professional AI content!Follow Now →

How to Use AI to Write Code: The Prompt Engineering Guide for Devs

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.

A
AiTechWorlds Team
May 27, 2026 8 min read
📱

Get more content like this on Telegram!

Daily AI tips, notes & resources — free

Join Free →

How to Use AI to Write Code: The Prompt Engineering Guide for Devs

The first time I used AI to write code seriously, I spent 30 minutes trying to get it to generate a working database query. I got four versions, none of which ran without modification. I gave up and wrote it manually.

Six months later, I was generating production-quality React components, TypeScript functions, and Prisma schema definitions in minutes. The underlying AI hadn't changed dramatically. My prompting had.

The gap between developers who get 2× productivity gains from AI coding tools and developers who get frustrated and give up is almost entirely in how they communicate with the AI. AI-assisted coding is a skill, and like all skills, it gets dramatically better with deliberate practice.

In this guide, you'll get the specific prompts, templates, and techniques that make AI coding tools actually useful — covering 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)"

Without types, AI generates JavaScript-like loosely-typed code. With types, it 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."

AI will omit error handling if you don't ask for it explicitly.

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:
- [What it does step 1]
- [What it does step 2]
- [What it returns]

Input validation:
- [What inputs to validate]
- [How to handle invalid inputs]

Error handling:
- [Error case 1] → [how to handle]
- [Error case 2] → [how to handle]

Performance requirements:
- [Any constraints: timeout, max iterations, etc.]

Code style:
- [Your conventions: async/await vs promises, etc.]
- TypeScript with strict types
- [Your import patterns]

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:
- [prop]: [type] ([required/optional], [description])
- [prop]: [type]

Behavior:
- [What it renders]
- [User interaction handling]
- [State management requirements]

Styling:
- [CSS approach: Tailwind/CSS modules/styled-components]
- [Key design requirements]

Performance:
- [Memoization requirements]
- [Lazy loading requirements]

Do NOT:
- Use class components
- Import unused dependencies
- Use inline styles except where necessary

API 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:
- [Authentication middleware name]
- [Rate limiting]

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:
- [attempt 1]
- [attempt 2]

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 works

Intermittent 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:
- [your hypothesis 1]
- [your hypothesis 2]

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 changes

Code 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.


Frequently Asked Questions

What are the best prompts for AI code generation?

Include language/framework, function signature, input/output types, explicit error handling requirements, and coding conventions. 'Write a login function' produces generic code; a specific prompt with types, error cases, and stack details produces production-ready code.

Should I use ChatGPT or GitHub Copilot for coding?

Use both for different things. Copilot for inline completion and continuing existing patterns. ChatGPT/Claude for generating complete functions from descriptions, complex debugging, code review, and architecture discussion.

Can AI write production-quality code?

AI generates a high-quality first draft that requires review. Common issues: missing input validation, insecure randomness, SQL injection risks, incomplete error handling. Never deploy security-sensitive AI code without thorough audit.

How do I get AI to write code that fits my codebase?

Provide existing code for similar functionality, your stack and versions, coding conventions, and examples of your error handling patterns. The more codebase context you provide, the more the output will match your patterns.

What's the best way to use AI for debugging?

Use chain-of-thought: paste the error, the code, expected vs actual behavior, and what you've tried. Ask the AI to trace through execution line by line and identify where behavior diverges. This finds root causes rather than symptom fixes.

Share this article:

Frequently Asked Questions

The most effective code prompts include: (1) Language and framework specification ('Write a TypeScript function using Prisma'), (2) Function signature or interface definition, (3) Input/output examples or test cases, (4) Explicit error handling requirements, (5) Performance or security constraints. The most common mistake is asking for code without specifying types, error cases, or the coding standards expected. 'Write a login function' produces generic code; 'Write a TypeScript async loginUser function that validates email/password against Supabase auth, returns a JWT, and handles AuthError with specific error messages' produces production-ready code.
A

AiTechWorlds Team

✓ Verified Writer

The AiTechWorlds team is passionate about AI, technology, and education. We create high-quality, research-backed content to help you learn, grow, and succeed in the modern digital world.

Related Articles

10K+ Members Growing Daily

Get Free AI Notes Daily

Join AiTechWorlds on Telegram and get daily AI tips, prompt engineering templates, coding resources, and exclusive content — 100% free!

📚 Free Study Notes🤖 AI Tips Daily⚡ Prompt Templates💻 Coding Resources
Join Free Channel

No spam. Leave anytime.

!