15 Prompts for Python Code Generation: From Simple Scripts to FastAPI

Introduction

Python remains one of the most versatile and beginner-friendly programming languages in 2026. Whether you're automating a mundane task, scraping data, or building a high-performance web API, the right prompt can save you hours of manual coding. Over the past few years, AI-assisted code generation has matured from a novelty into a daily productivity tool for developers. This article collects 15 battle-tested prompts for generating Python code, ranging from quick scripts to production-ready FastAPI applications. Each prompt includes a concrete usage example and practical tips to get the most out of your AI assistant.

Section 1: Simple Scripts (Prompts 1–5)

These prompts are ideal for automating repetitive tasks or generating utility scripts. They assume no prior context and produce self-contained, runnable code.

Prompt 1: File Renaming Script

Prompt: "Write a Python script that renames all files in a given directory by replacing spaces with underscores. The script should accept the directory path as a command-line argument."

Usage Example: You have a folder with files like 'my report.pdf' and need them renamed to 'my_report.pdf'. Run python rename.py /path/to/folder.

Why it works: The AI will generate a script using os and sys modules, handle edge cases like non-existent directories, and include a dry-run mode if you ask. This is a classic task that teaches file I/O and argument parsing.

Prompt 2: CSV to JSON Converter

Prompt: "Create a Python function that reads a CSV file and returns a list of dictionaries. Include error handling for missing files and malformed rows."

Usage Example: You have a CSV with columns 'name, email, age' and need JSON for a web app. The function can be imported and used in other scripts.

Why it works: This prompt focuses on data transformation, a common need. The AI will likely use csv.DictReader and add type conversion hints.

Prompt 3: Web Scraper with BeautifulSoup

Prompt: "Write a Python script using requests and BeautifulSoup to extract all article headlines from a news website. The script should output the results as a plain text list."

Usage Example: You want to monitor headlines from Hacker News or a tech blog. Run the script to get a quick snapshot.

Why it works: Web scraping is a common entry point for Python learners. The AI will generate code that handles HTTP requests, parses HTML, and extracts text, with comments explaining each step.

Prompt 4: Password Generator

Prompt: "Generate a Python script that creates a random password of specified length, including uppercase, lowercase, digits, and special characters. Use Python's secrets module for security."

Usage Example: You need a strong password for a new account. Run python passgen.py 16 to get a 16-character password.

Why it works: This prompt encourages use of secure random generators (secrets instead of random) and teaches string manipulation.

Prompt 5: Directory Tree Viewer

Prompt: "Write a Python script that prints a directory tree structure similar to the tree command, but only for directories. Accept the root path as an argument."

Usage Example: You want to visualize the folder structure of a project without installing external tools.

Why it works: The AI will use recursive os.listdir() and os.path.isdir() to traverse directories, helping you understand recursion.

Section 2: Data Analysis & Automation (Prompts 6–10)

These prompts are more advanced and often involve libraries like pandas, numpy, or matplotlib. They produce scripts that can be integrated into larger data pipelines.

Prompt 6: DataFrame Summary Statistics

Prompt: "Write a pandas script that reads a CSV file, prints basic statistics (mean, median, standard deviation) for all numeric columns, and saves the summary to a new CSV file."

Usage Example: You have a dataset of sales figures and need a quick statistical overview. The script automates what you'd otherwise do manually in Jupyter.

Why it works: This prompt teaches data aggregation and file output. The AI will use df.describe() and handle missing values.

Prompt 7: Email Sender with SMTP

Prompt: "Create a Python function that sends an email via SMTP using environment variables for credentials. The function should accept recipient, subject, and body as parameters."

Usage Example: You want to automate notifications from a cron job. The function can be called from any script without hardcoding passwords.

Why it works: Email automation is a staple of backend scripts. The AI will use smtplib and os.environ for secure credential handling.

Prompt 8: API Client for OpenWeatherMap

Prompt: "Write a Python script that fetches current weather data from the OpenWeatherMap API for a given city. Use an API key from an environment variable and display temperature, humidity, and description."

Usage Example: You want to build a weather dashboard or get alerts for specific conditions.

Why it works: This prompt teaches REST API interaction with requests, JSON parsing, and API key management.

Prompt 9: Log File Analyzer

Prompt: "Generate a Python script that analyzes an Apache access log file and returns the top 10 IP addresses by request count. Use regex to parse log lines."

Usage Example: You need to identify the most active visitors or potential attackers on your web server.

Why it works: Log analysis is a real-world task. The AI will use re and collections.Counter for efficient counting.

Prompt 10: Image Resizer with Pillow

Prompt: "Write a Python script that resizes all JPEG images in a folder to a specified width while maintaining aspect ratio. Output the resized images to a new folder."

Usage Example: You have a batch of product photos that need to be standardized for an e-commerce site.

Why it works: Image processing is common in automation. The AI will use PIL.Image and include error handling for unsupported formats.

Section 3: FastAPI Web Services (Prompts 11–15)

FastAPI has become the go-to framework for building Python APIs in 2026 due to its performance, automatic OpenAPI docs, and async support. These prompts generate production-ready code with best practices.

Prompt 11: Basic CRUD API for a To-Do List

Prompt: "Create a FastAPI application with SQLite that supports Create, Read, Update, and Delete operations for a to-do item (id, title, completed). Include request validation using Pydantic models."

Usage Example: You want to build a minimal task manager backend. The generated code will include endpoints like GET /todos, POST /todos, etc.

Why it works: This prompt covers the essentials: FastAPI app setup, SQLAlchemy ORM (or SQLite directly), and Pydantic schemas. The AI will produce a single main.py file with all routes.

Prompt 12: User Authentication with JWT

Prompt: "Extend a FastAPI application with user registration and login endpoints using JWT tokens. Store passwords as hashed values using bcrypt."

Usage Example: You're building an app that requires user accounts. This prompt generates secure authentication flow.

Why it works: JWT authentication is a critical skill. The AI will include python-jose for JWT generation and passlib for password hashing.

Prompt 13: File Upload Endpoint with Validation

Prompt: "Write a FastAPI endpoint that accepts file uploads, validates the file type (only PDF and images), and saves them to a local directory. Return the file URL."

Usage Example: You need a file upload feature for a document management system.

Why it works: File handling in FastAPI is straightforward with UploadFile. The AI will add MIME type checks and size limits.

Prompt 14: Async Background Task with Celery

Prompt: "Create a FastAPI application that offloads a long-running task (e.g., sending emails) to a Celery worker. Use Redis as the message broker."

Usage Example: Your API needs to send confirmation emails without blocking the response. Celery handles the async processing.

Why it works: This prompt teaches async task queues, a common requirement for scalable APIs. The AI will generate both the FastAPI app and the Celery task definition.

Prompt 15: Rate-Limiting Middleware

Prompt: "Add rate-limiting middleware to a FastAPI application using slowapi. Limit requests to 10 per minute per IP address."

Usage Example: You want to protect your API from abuse. The middleware returns a 429 status code when exceeded.

Why it works: Rate limiting is a security best practice. The AI will import slowapi and configure it with a custom limit.

Conclusion

These 15 prompts represent a spectrum of Python use cases, from quick scripting to robust web services. The key to effective AI code generation is specificity: always include input/output formats, error handling expectations, and library preferences. As you experiment, you'll develop your own library of prompts that match your workflow. Remember to review and test all generated code—while AI assistants are powerful, they can make subtle mistakes, especially with edge cases. Start with the simple scripts, then gradually move to FastAPI prompts as you gain confidence. Happy coding!

← All posts

Comments