Why You Need Precise Prompts for Python Code Generation
Writing Python code with AI assistants like ChatGPT, Claude, or GitHub Copilot has become a daily practice for many developers. However, the difference between a generic, broken script and production-ready code often lies in how you phrase your prompt. A vague request like "write a Python script to read a CSV file" yields a basic csv.reader loop, while a precise prompt can generate error-handling, type hints, logging, and even a CLI interface.
This article provides 15 ready-to-use prompts for generating Python code, ranging from simple automation scripts to fully functional FastAPI microservices. Each prompt is tested and designed to be copy-pasted into your preferred AI tool. We'll also explain why each prompt works and how to adapt it to your specific use case.
How to Structure a Python Code Generation Prompt
Before diving into the prompts, let's establish a universal structure that maximizes output quality:
| Component | Example | Why It Matters |
|---|---|---|
| Role | "You are a senior Python developer" | Sets expertise level |
| Context | "I'm building a data pipeline for customer analytics" | Provides business logic |
| Task | "Write a script that reads a CSV and generates a monthly report" | Clear goal |
| Constraints | "Use only standard library, no external packages" | Limits dependencies |
| Output format | "Return the code in a single Python file with comments" | Easy to copy and run |
| Example input/output | "Input: orders.csv, Output: report_2026-07.html" | Clarifies expectations |
15 Prompts for Python Code Generation
Prompt 1: File Renaming Script with Logging
Task: Rename all .jpg files in a folder to include a date prefix.
Prompt:
You are a Python developer. Generate a script that renames all .jpg files in a given directory by prepending the current date (YYYY-MM-DD) to the filename. Requirements:
- Accept the directory path as a command-line argument using argparse.
- Add a --dry-run flag that only prints what would be renamed without actually renaming.
- Use the logging module to output actions (INFO) and errors (ERROR).
- Handle duplicate filenames by appending a counter (e.g., _1, _2).
- Include type hints for all functions.
Example: python rename_jpg.py /path/to/photos --dry-run
Why it works: Specifies CLI interface, dry-run capability, error handling, and logging — all essential for production scripts.
Prompt 2: Web Scraper with BeautifulSoup and Requests
Task: Scrape product prices from an e-commerce page.
Prompt:
Write a Python script using requests and BeautifulSoup4 to scrape product names and prices from a given URL. The HTML structure uses <div class="product-card"> for each product, with the name in an <h2> tag and price in a <span class="price">. Requirements:
- Accept URL from command line.
- Handle HTTP errors (404, 500) with retry logic (max 3 attempts).
- Save results to a CSV file with columns: product_name, price, scraped_at (timestamp).
- Use a random User-Agent header to avoid blocking.
- Add try/except for parsing failures.
Why it works: Gives exact HTML structure, error handling, and output format — eliminates guesswork.
Prompt 3: CSV Data Cleaner with Pandas
Task: Remove duplicates and fill missing values in a CSV.
Prompt:
You are a data engineer. Write a Python script using pandas to clean a CSV file. Requirements:
- Accept input and output filenames as command-line arguments.
- Remove duplicate rows based on all columns.
- Fill missing numeric values with the column mean.
- Fill missing string values with 'Unknown'.
- Strip whitespace from all string columns.
- Save the cleaned DataFrame to the output CSV.
- Print summary statistics before and after cleaning (row count, missing values).
- Use argparse for CLI arguments.
Why it works: Defines precise cleaning steps and output expectations.
Prompt 4: JSON to YAML Converter with Validation
Task: Convert a JSON file to YAML format with schema validation.
Prompt:
Generate a Python script that converts a JSON file to YAML using PyYAML. Requirements:
- Accept input JSON file and output YAML file via command-line arguments.
- Validate that the JSON has a top-level key 'version' that is a string.
- If validation fails, print a clear error message and exit with code 1.
- Preserve the order of keys using OrderedDict.
- Add a --pretty flag that formats the YAML with indentation of 4 spaces.
- Include type hints and docstrings for each function.
Why it works: Includes validation, formatting options, and error handling — typical for data pipelines.
Prompt 5: Simple REST API Client with Retry Logic
Task: Fetch data from a public API and handle rate limiting.
Prompt:
Write a Python script using the requests library to fetch data from https://api.example.com/users?page=1. Requirements:
- Handle pagination: loop through all pages until an empty list is returned.
- Implement exponential backoff retry (1s, 2s, 4s) on 429 and 5xx errors.
- Save all user data to a JSON file.
- Use a session object to reuse connections.
- Add proper exception handling for network errors.
- Log each API call and its status code.
Why it works: Specifically addresses pagination and rate limiting — two common API issues.
Prompt 6: Database Migration Script (SQLite to PostgreSQL)
Task: Migrate data from SQLite to PostgreSQL using SQLAlchemy.
Prompt:
You are a backend developer. Create a Python migration script that copies all tables from an SQLite file to a PostgreSQL database. Use SQLAlchemy ORM. Requirements:
- Connect to SQLite using sqlite:///source.db.
- Connect to PostgreSQL using the DATABASE_URL environment variable.
- For each table, fetch all rows and insert them into the PostgreSQL equivalent.
- Handle foreign key constraints by disabling them temporarily with SET session_replication_role = 'replica'.
- Print progress for each table.
- Roll back the entire migration if any table fails.
- Use asyncpg for asynchronous PostgreSQL connection if possible.
Why it works: Covers real-world migration challenges like foreign keys and rollback.
Prompt 7: CLI Tool for File Encryption (AES)
Task: Encrypt and decrypt files using AES-256.
Prompt:
Write a Python CLI tool for encrypting and decrypting files using AES-256-GCM. Use the cryptography library. Requirements:
- Two subcommands: encrypt and decrypt, using argparse subparsers.
- For encrypt: generate a random salt and derive a key from a password using PBKDF2 (100,000 iterations).
- Store salt and nonce in the output file header (first 16 bytes salt, next 12 bytes nonce).
- For decrypt: read salt and nonce from the header, derive key, and decrypt.
- Add a --overwrite flag to allow overwriting existing output files.
- Handle large files by processing in 64KB chunks.
Why it works: Implements cryptographic best practices (salt, PBKDF2, authenticated encryption).
Prompt 8: Data Validation with Pydantic (v2)
Task: Validate incoming JSON data against a schema.
Prompt:
Create a Python script using Pydantic v2 that validates a JSON input file containing a list of users. Each user must have:
- name: string, 1-100 characters
- email: string, valid email format
- age: integer, 18-120
- role: enum ('admin', 'user', 'guest')
- tags: list of strings, max 5 items
Requirements:
- Load JSON from a file path given as command-line argument.
- Validate each user with a Pydantic BaseModel.
- Collect all validation errors and print them in a readable format.
- If any user fails, exit with code 1.
- Save valid users to a new JSON file.
- Use Field validators for custom logic (e.g., ensure email domain is not 'example.com').
Why it works: Leverages Pydantic's validation power for real-world API payloads.
Prompt 9: Asynchronous File Downloader (aiohttp)
Task: Download multiple files concurrently from a list of URLs.
Prompt:
Write an asynchronous Python script using aiohttp and asyncio to download files from a list of URLs provided in a text file (one URL per line). Requirements:
- Limit concurrent downloads to 5 using a semaphore.
- Show a progress bar using tqdm.
- Save files with the original filename from the URL (last path segment).
- Handle HTTP errors: skip failed URLs and log them.
- Retry failed downloads up to 3 times with a 2-second delay.
- Use asyncio.create_task for scheduling.
Why it works: Demonstrates real async patterns (semaphore, progress bar, retry).
Prompt 10: FastAPI CRUD with SQLAlchemy and Pydantic
Task: Create a RESTful API for managing a list of items.
Prompt:
You are a senior backend developer using FastAPI. Create a complete CRUD API for an 'Item' resource with SQLite and SQLAlchemy. The Item model has:
- id: integer, primary key, auto-generated
- name: string, not null, max 255 chars
- description: string, optional
- price: float, must be >= 0
- created_at: datetime, auto-set on creation
Requirements:
- Use FastAPI with async endpoints.
- Use Pydantic v2 models for request/response validation.
- Use SQLAlchemy 2.0 style with async sessions.
- Implement endpoints: POST /items, GET /items, GET /items/{id}, PUT /items/{id}, DELETE /items/{id}.
- Add proper HTTP status codes (201 for create, 404 for not found).
- Include a health check endpoint GET /health.
- Add CORS middleware allowing all origins for development.
- Run with uvicorn on port 8000.
Why it works: Gives complete model, endpoints, and framework-specific instructions.
Prompt 11: FastAPI with JWT Authentication
Task: Add user registration, login, and protected routes.
Prompt:
Extend the FastAPI CRUD app with JWT-based authentication. Use python-jose for JWT and passlib for password hashing (bcrypt). Requirements:
- User model: id, username (unique), hashed_password.
- POST /register: accepts username and password, hashes password, returns user info (no password).
- POST /login: returns access token (expires in 30 minutes) and refresh token (7 days).
- POST /refresh: accepts refresh token, returns new access token.
- Protect all /items endpoints: require a valid Bearer token.
- Token payload includes sub (username) and exp.
- Use OAuth2PasswordBearer for token extraction.
- Add a GET /users/me endpoint returning current user info.
Why it works: Covers the full auth flow with refresh tokens — a common real requirement.
Prompt 12: FastAPI File Upload with Validation
Task: Accept image uploads, validate type and size, save to disk.
Prompt:
Create a FastAPI endpoint POST /upload that accepts a file upload. Requirements:
- Accept only JPEG and PNG images (check MIME type and file extension).
- Maximum file size: 5 MB.
- Save the file to the 'uploads/' directory with a UUID-based filename preserving the extension.
- Return the filename and URL in the response.
- Handle cases where the directory doesn't exist (create it).
- Use File and UploadFile from fastapi.
- Add a GET /uploads/{filename} endpoint to serve the file.
- Log each upload with timestamp and filename.
Why it works: Addresses file validation, storage, and serving — essential for media APIs.
Prompt 13: FastAPI Background Tasks (Email Sending)
Task: Process long-running tasks asynchronously after returning a response.
Prompt:
Write a FastAPI endpoint POST /send-email that accepts email data (to, subject, body) and uses BackgroundTasks to send the email via SMTP (smtplib). Requirements:
- Validate email fields using Pydantic: to must be valid email, subject non-empty, body non-empty.
- Return immediate response: {"status": "queued", "message_id": "..."} with a UUID.
- Background task: connect to SMTP server (use environment variables SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS).
- Log success or failure of each email send.
- Store send status in a simple JSON file (as a message queue simulation).
- Handle SMTP connection errors gracefully (log, don't crash).
Why it works: Shows practical use of BackgroundTasks for non-blocking operations.
Prompt 14: FastAPI WebSocket Chat
Task: Build a simple real-time chat using WebSockets.
Prompt:
Create a FastAPI application with WebSocket endpoint /ws/{room_name}. Requirements:
- Clients can join any room by connecting to /ws/{room_name}.
- When a client sends a JSON message {"username": "Alice", "text": "Hello"}, broadcast it to all other clients in the same room.
- Maintain a dict of connected clients per room: room_name -> list of WebSocket connections.
- Handle client disconnect: remove from room and notify others with a system message.
- Limit room names to alphanumeric characters and hyphens.
- Add a REST endpoint GET /rooms returning list of active rooms.
- Use asyncio queues for managing messages if needed.
Why it works: Covers WebSocket basics with room management — a common pattern.
Prompt 15: Full-Featured FastAPI Microservice with Docker
Task: Combine all previous concepts into a production-ready microservice.
Prompt:
You are building a production-ready FastAPI microservice for a task management system. Generate the complete codebase including:
1. main.py: FastAPI app with CORS, lifespan events (create tables on startup).
2. models.py: SQLAlchemy models for User and Task.
3. schemas.py: Pydantic models for request/response.
4. auth.py: JWT authentication with login, register, refresh.
5. routers/tasks.py: CRUD endpoints for tasks (only owners can modify).
6. routers/users.py: User profile endpoints.
7. database.py: Async SQLite database setup.
8. Dockerfile: Multi-stage build, Python 3.12 slim, expose port 8000.
9. docker-compose.yml: Service with environment variables for SECRET_KEY, DATABASE_URL.
10. requirements.txt: All dependencies with pinned versions.
Requirements:
- Use asyncpg for PostgreSQL (change DATABASE_URL to postgresql+asyncpg://...).
- Add rate limiting using slowapi.
- Add request logging middleware.
- Use .env file for configuration via pydantic-settings.
- Include pytest tests for all endpoints.
Why it works: Covers architecture, deployment, and testing — a complete blueprint.
Tips for Customizing Prompts
- Specify the Python version if you need modern features (e.g., "Python 3.12 with match-case").
- Mention your OS if file paths matter (e.g., "Windows paths with backslashes").
- Add a "do not use" list to exclude unwanted libraries (e.g., "Do not use pandas, only csv module").
- Request docstrings and comments for maintainability.
- Ask for a test file alongside the main script — AI can generate pytest files too.
Conclusion
Generating Python code with AI is a superpower, but only if you craft your prompts with precision. The 15 prompts above cover the most common scenarios for both scripting and FastAPI development. Start by copying them directly, then tweak the parameters (URLs, field names, file paths) to match your project. Over time, you'll develop an intuition for what details make a prompt produce production-quality code instead of a toy example.
Remember: the best prompts include context, constraints, and concrete examples. Treat your AI assistant as a junior developer who needs clear instructions — and you'll get code that works the first time.
Last updated: July 2026
Comments