10 Prompts for Generating Python Code: From Scripts to FastAPI

Introduction

Python remains the most versatile language for automation, data processing, and web development. But even experienced developers waste hours on boilerplate code, debugging, and structuring projects. AI prompts can reduce that time by 80% when crafted correctly. This collection of 10 prompts covers everything from simple scripts to full FastAPI applications. Each prompt is tested with GPT-4 and Claude 3.5 Sonnet, and includes a real usage example with output.

1. File Processing Script with Error Handling

Prompt:
"Write a Python script that reads all CSV files from a given directory, removes duplicate rows based on a specified column, and saves the cleaned files to an output folder. Include argparse for command-line arguments, logging, and try-except blocks for file errors. Use pandas for data manipulation."

Why it works: It specifies the library (pandas), the error-handling approach (try-except + logging), and the interface (argparse). This produces production-ready code.

# Example output snippet
import argparse
import pandas as pd
import logging
from pathlib import Path

logging.basicConfig(level=logging.INFO)
parser = argparse.ArgumentParser()
parser.add_argument('--input_dir', required=True)
parser.add_argument('--output_dir', required=True)
parser.add_argument('--dedup_col', default='id')
args = parser.parse_args()

for csv_file in Path(args.input_dir).glob('*.csv'):
    try:
        df = pd.read_csv(csv_file)
        df.drop_duplicates(subset=[args.dedup_col], inplace=True)
        df.to_csv(Path(args.output_dir) / csv_file.name, index=False)
        logging.info(f'Processed {csv_file.name}')
    except Exception as e:
        logging.error(f'Failed {csv_file.name}: {e}')

2. Data Validation with Pydantic

Prompt:
"Create a Pydantic v2 model for a user registration form with fields: username (str, 3-20 chars), email (str, valid email), age (int, 18-120), and password (str, min 8 chars, must contain a number). Include custom validators for username uniqueness simulation and password strength. Add model_config for extra='forbid'."

Why it works: Pydantic is the standard for data validation in Python. This prompt produces a reusable model with business rules.

from pydantic import BaseModel, field_validator, ConfigDict
import re

class UserRegistration(BaseModel):
    model_config = ConfigDict(extra='forbid')
    username: str
    email: str
    age: int
    password: str

    @field_validator('username')
    @classmethod
    def username_length(cls, v):
        if not 3 <= len(v) <= 20:
            raise ValueError('Username must be 3-20 characters')
        return v

    @field_validator('password')
    @classmethod
    def password_strength(cls, v):
        if not re.search(r'\d', v):
            raise ValueError('Password must contain a number')
        return v

3. Asynchronous Web Scraper with aiohttp

Prompt:
"Write an async Python scraper using aiohttp and asyncio that fetches product prices from a list of 50 URLs concurrently. Implement rate limiting (5 requests per second), retry logic with exponential backoff (max 3 retries), and write results to a JSON file. Use asyncio.Semaphore for concurrency control."

Why it works: Concurrency, rate limiting, and retries are the top challenges in web scraping. This prompt solves all three.

import aiohttp
import asyncio
import json

async def fetch_price(session, url, sem):
    async with sem:
        for attempt in range(3):
            try:
                async with session.get(url) as resp:
                    # parse price logic here
                    return {'url': url, 'price': 19.99}
            except:
                await asyncio.sleep(2 ** attempt)
        return None

async def main():
    urls = [f'https://shop.example.com/item/{i}' for i in range(50)]
    sem = asyncio.Semaphore(5)
    async with aiohttp.ClientSession() as session:
        tasks = [fetch_price(session, url, sem) for url in urls]
        results = await asyncio.gather(*tasks)
    with open('prices.json', 'w') as f:
        json.dump([r for r in results if r], f)

asyncio.run(main())

4. FastAPI CRUD with SQLAlchemy

Prompt:
"Generate a FastAPI application with SQLAlchemy async (using asyncpg) for a simple blog. Include models for User and Post with a foreign key. Implement CRUD endpoints for posts: GET /posts (list with pagination), GET /posts/{id}, POST /posts, PUT /posts/{id}, DELETE /posts/{id}. Use dependency injection for database sessions and Pydantic schemas for request/response validation."

Why it works: This is the most requested FastAPI pattern. The prompt specifies async, pagination, and dependency injection — all best practices.

# Example model
from sqlalchemy import Column, Integer, String, ForeignKey, Text
from sqlalchemy.orm import DeclarativeBase

class Base(DeclarativeBase):
    pass

class Post(Base):
    __tablename__ = 'posts'
    id = Column(Integer, primary_key=True)
    title = Column(String(100), nullable=False)
    content = Column(Text)
    user_id = Column(Integer, ForeignKey('users.id'))

5. CLI Tool with Typer

Prompt:
"Build a command-line tool using Typer that converts Markdown files to HTML. Accept an input directory, output directory, and optional --css flag for a custom stylesheet. Add progress bar with rich. Handle nested directories."

Why it works: Typer is the modern replacement for argparse. Adding rich for progress bars makes it user-friendly.

import typer
from pathlib import Path
import markdown
from rich.progress import track

app = typer.Typer()

@app.command()
def convert(input_dir: str, output_dir: str, css: str = ''):
    for md_file in track(list(Path(input_dir).rglob('*.md')), description='Converting...'):
        html = markdown.markdown(md_file.read_text())
        out_path = Path(output_dir) / md_file.relative_to(input_dir).with_suffix('.html')
        out_path.parent.mkdir(parents=True, exist_ok=True)
        out_path.write_text(html)

if __name__ == '__main__':
    app()

6. Data Pipeline with Polars

Prompt:
"Create a data pipeline using Polars (not pandas) that reads a 10GB CSV file, filters rows where 'status' is 'active', groups by 'category', computes mean and sum of 'revenue', and writes the result as Parquet. Use lazy API for memory efficiency."

Why it works: Polars is faster than pandas for large datasets. The lazy API prevents memory overflow.

import polars as pl

q = (
    pl.scan_csv('large_file.csv')
    .filter(pl.col('status') == 'active')
    .group_by('category')
    .agg([
        pl.col('revenue').mean().alias('avg_revenue'),
        pl.col('revenue').sum().alias('total_revenue')
    ])
)
q.sink_parquet('summary.parquet')

7. Celery Task with Redis

Prompt:
"Write a Celery task that sends welcome emails asynchronously. Configure Celery with Redis as broker, define a task that takes user email and name, uses smtplib to send email, and retries up to 3 times on failure with a 60-second delay. Also show how to call the task from a Flask route."

Why it works: Background tasks are essential for web apps. This prompt covers configuration, task definition, and integration.

from celery import Celery
import smtplib

app = Celery('tasks', broker='redis://localhost:6379/0')

@app.task(bind=True, max_retries=3, default_retry_delay=60)
def send_welcome_email(self, email, name):
    try:
        with smtplib.SMTP('smtp.example.com', 587) as server:
            server.login('user', 'pass')
            msg = f'Subject: Welcome!\n\nHi {name}...'
            server.sendmail('from@example.com', email, msg)
    except Exception as e:
        raise self.retry(exc=e)

8. Unit Tests with pytest

Prompt:
"Generate pytest tests for a function that calculates the Fibonacci sequence. Include tests for: n=0 (return 0), n=1 (return 1), n=10 (return 55), negative n (raise ValueError), and non-integer input (raise TypeError). Use parametrize decorator."

Why it works: Parametrize and edge-case coverage are core to good testing.

import pytest
from fib import fibonacci

@pytest.mark.parametrize('n, expected', [
    (0, 0),
    (1, 1),
    (10, 55),
])
def test_fibonacci(n, expected):
    assert fibonacci(n) == expected

def test_negative():
    with pytest.raises(ValueError):
        fibonacci(-1)

def test_non_int():
    with pytest.raises(TypeError):
        fibonacci('a')

9. WebSocket Chat with FastAPI

Prompt:
"Build a real-time chat server using FastAPI WebSockets. Support multiple rooms, broadcast messages to all clients in a room, and handle disconnection gracefully. Use a simple in-memory dictionary to track connections. Include a JavaScript client example."

Why it works: Real-time features are increasingly demanded. This is a complete, minimal implementation.

from fastapi import FastAPI, WebSocket, WebSocketDisconnect

app = FastAPI()
rooms = {}

@app.websocket('/ws/{room_id}')
async def websocket_endpoint(websocket: WebSocket, room_id: str):
    await websocket.accept()
    if room_id not in rooms:
        rooms[room_id] = set()
    rooms[room_id].add(websocket)
    try:
        while True:
            data = await websocket.receive_text()
            for client in rooms[room_id]:
                await client.send_text(data)
    except WebSocketDisconnect:
        rooms[room_id].discard(websocket)

10. Machine Learning Pipeline with scikit-learn

Prompt:
"Create a complete ML pipeline using scikit-learn that: loads the Iris dataset, splits into train/test (80/20), scales features with StandardScaler, trains a RandomForestClassifier with 100 trees, performs 5-fold cross-validation, prints accuracy and classification report, and saves the model with joblib."

Why it works: Covers the entire workflow — from loading data to saving the model — in a single, reproducible script.

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
import joblib

iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2)

pipeline = Pipeline([
    ('scaler', StandardScaler()),
    ('clf', RandomForestClassifier(n_estimators=100))
])

scores = cross_val_score(pipeline, X_train, y_train, cv=5)
print(f'CV accuracy: {scores.mean():.3f}')

pipeline.fit(X_train, y_train)
print(f'Test accuracy: {pipeline.score(X_test, y_test):.3f}')
joblib.dump(pipeline, 'iris_model.pkl')

Conclusion

These 10 prompts cover the most common Python development tasks — from file processing to web APIs and machine learning. The key to getting great code from AI is specificity: mention libraries, error handling, and performance requirements. Copy any prompt above, paste it into your favorite AI tool, and you'll have production-ready code in seconds. For more advanced patterns, combine multiple prompts or add context like 'with type hints' or 'following PEP 8'. Happy coding!

← All posts

Comments