10 Prompts for Python Code Generation: From Scripts to FastAPI

10 Prompts for Python Code Generation: From Scripts to FastAPI

Python remains one of the most versatile programming languages in 2026, powering everything from simple automation scripts to complex web APIs. With the rise of large language models (LLMs) like GPT-4o, Claude 3.5, and specialized code assistants, generating reliable Python code with well-crafted prompts has become a practical skill for developers, data scientists, and engineers. This article provides ten ready-to-use prompts for Python code generation, ranging from basic scripts to production-ready FastAPI applications. Each prompt includes a specific task description, an explanation of its use case, and a usage example. By mastering these prompts, you can accelerate your development workflow, reduce boilerplate, and focus on solving higher-level problems.

Why Use Prompts for Python Code Generation?

Prompt engineering is the practice of designing input instructions that guide an AI model to produce desired outputs. For Python code generation, effective prompts reduce ambiguity, enforce coding standards, and incorporate context such as libraries, error handling, and performance constraints. According to a 2025 study by GitHub, developers using AI-assisted coding tools reported a 55% increase in task completion speed for routine functions. However, generic prompts like "write a Python script" often yield incomplete or incorrect results. Specific prompts—those that define input/output formats, dependencies, and edge cases—dramatically improve output quality.

Prompt 1: Basic Script to Parse a CSV File

Task: Generate a Python script that reads a CSV file, filters rows based on a condition, and writes the result to a new CSV file.

Explanation: This prompt is ideal for data cleaning or ETL (extract, transform, load) tasks. It teaches the AI to include file handling, CSV parsing with the csv module, and basic filtering logic. The prompt specifies the input file, output file, and filtering condition.

Prompt text:

Write a Python script that:
- Reads a CSV file named 'input.csv' with columns 'name', 'age', 'city'.
- Filters rows where age > 30.
- Writes the filtered rows to 'output.csv' with the same columns.
- Uses the built-in csv module.
- Includes error handling for missing files.

Usage example: Save the generated script as filter_csv.py and run python filter_csv.py. The script will create output.csv with only rows where the age column exceeds 30. If input.csv is missing, it prints a clear error message.

Input row Age Output?
Alice, 25, NYC 25 No
Bob, 35, LA 35 Yes

Prompt 2: Web Scraper with BeautifulSoup and Requests

Task: Generate a script that scrapes product titles and prices from an e-commerce page.

Explanation: This prompt is for extracting structured data from HTML. It specifies the libraries (requests, BeautifulSoup), the target CSS selectors, and the output format (JSON). This avoids vague scraping attempts.

Prompt text:

Write a Python script that:
- Sends a GET request to 'https://example.com/products'.
- Parses the HTML with BeautifulSoup.
- Extracts all product titles (class 'product-title') and prices (class 'price').
- Stores results as a list of dictionaries: [{'title': '...', 'price': '...'}].
- Saves the list to 'products.json'.
- Handles HTTP errors (e.g., 404, 500) gracefully.

Usage example: Run the script to fetch product data and save it as a JSON file. This is useful for price monitoring or inventory analysis.

Prompt 3: Data Analysis with Pandas and Matplotlib

Task: Generate a script that analyzes a dataset and creates a visualization.

Explanation: This prompt combines data manipulation (pandas) and plotting (matplotlib). It specifies the analysis goal (e.g., mean, median) and the chart type, ensuring the output is actionable.

Prompt text:

Write a Python script that:
- Loads 'sales.csv' with columns 'date', 'revenue', 'region'.
- Groups by region and calculates the total revenue per region.
- Creates a bar chart showing total revenue for each region.
- Saves the chart as 'revenue_by_region.png'.
- Uses pandas for data handling and matplotlib for plotting.

Usage example: After running, you get both a printed summary and a visual chart. This is common in weekly sales reporting.

Prompt 4: Asynchronous API Client with aiohttp

Task: Generate an async function that fetches data from multiple endpoints concurrently.

Explanation: Asynchronous programming is critical for I/O-bound tasks like API calls. This prompt includes asyncio and aiohttp, and specifies concurrency limits to avoid overwhelming servers.

Prompt text:

Write an async Python function using aiohttp that:
- Takes a list of URLs.
- Fetches each URL concurrently, with a maximum of 5 simultaneous requests.
- Returns a list of response texts.
- Handles timeouts (5 seconds per request) and connection errors.
- Use asyncio.gather for concurrency.

Usage example: Call await fetch_all([url1, url2, url3]) to get responses in parallel, reducing total fetch time from sum to max.

Prompt 5: FastAPI CRUD Endpoint with SQLite

Task: Generate a complete FastAPI app with a CRUD (Create, Read, Update, Delete) endpoint for a simple model.

Explanation: FastAPI is a modern web framework for building APIs. This prompt produces a runnable app with SQLite via SQLAlchemy, including request validation with Pydantic.

Prompt text:

Write a FastAPI application that:
- Uses SQLite database (via SQLAlchemy) with a table 'items' (id integer, name text, price float).
- Provides REST endpoints:
  - POST /items/ - create a new item.
  - GET /items/{id} - read an item by id.
  - PUT /items/{id} - update an item.
  - DELETE /items/{id} - delete an item.
- Uses Pydantic models for request/response validation.
- Runs on port 8000 with uvicorn.
- Includes a health check endpoint GET /health.

Usage example: Save as main.py, run uvicorn main:app --reload, and test with curl http://localhost:8000/items/1. This is the foundation for many microservices.

Prompt 6: FastAPI with Dependency Injection and Authentication

Task: Generate a FastAPI app with dependency injection for database sessions and JWT authentication.

Explanation: Real-world APIs require authentication. This prompt builds on the previous one by adding JWT (JSON Web Tokens) and dependency injection, following FastAPI best practices.

Prompt text:

Write a FastAPI application that:
- Uses SQLAlchemy async with PostgreSQL (connection string as environment variable DATABASE_URL).
- Implements JWT authentication: POST /token returns access token, GET /users/me returns current user.
- Uses dependency injection to provide database sessions to endpoints.
- Includes a User model with username and hashed password.
- All endpoints except /token require valid JWT.
- Use python-jose for JWT and passlib for password hashing.

Usage example: This serves as a secure backend for a web or mobile app. ASI Biont supports connecting to PostgreSQL databases via its API integration layer—learn more at asibiont.com/courses.

Prompt 7: Unit Tests with pytest

Task: Generate a test suite for a given Python function using pytest.

Explanation: Testing is essential for code reliability. This prompt covers parameterized tests, fixtures, and edge cases.

Prompt text:

Write pytest tests for the following function:

def calculate_discount(price: float, percent: float) -> float:
    """Return price after discount. percent is between 0 and 100."""
    if percent < 0 or percent > 100:
        raise ValueError("Percent must be 0-100")
    return price * (1 - percent / 100)

Include:
- A test for normal case (price=100, percent=20 -> 80.0).
- A test for zero discount.
- A test for 100% discount.
- A test for invalid percent (e.g., 150) that expects ValueError.
- Use pytest.mark.parametrize for multiple cases.

Usage example: Run pytest test_discount.py to verify the function works correctly across all cases.

Prompt 8: CLI Tool with argparse

Task: Generate a command-line interface (CLI) tool that accepts arguments and options.

Explanation: CLI tools are useful for automation. This prompt uses argparse to handle positional and optional arguments, with help text.

Prompt text:

Write a Python CLI tool using argparse that:
- Accepts a positional argument 'filename' (string).
- Has an optional '--verbose' flag.
- Has an optional '--output' argument to specify output file (default stdout).
- Reads the file, counts lines, words, and characters (like wc command).
- Prints the counts to the specified output.
- Includes error handling for file not found.

Usage example: Run python wordcount.py input.txt --verbose to see detailed counts.

Prompt 9: Data Validation with Pydantic

Task: Generate a Pydantic model for validating complex nested JSON data.

Explanation: Pydantic is widely used for data validation in FastAPI and other Python apps. This prompt covers nested models, custom validators, and field types.

Prompt text:

Write Pydantic v2 models for the following JSON structure:
{
  "user": {
    "name": "Alice",
    "email": "alice@example.com",
    "age": 30
  },
  "orders": [
    {"id": 1, "total": 49.99, "items": ["book", "pen"]}
  ]
}

Requirements:
- Validate that email is a valid email format.
- Age must be between 0 and 120.
- Each order total must be positive.
- Use custom validators for email and age.

Usage example: Parse incoming JSON with model.validate(json_data) to automatically raise errors for invalid data.

Prompt 10: Automation Script with Selenium

Task: Generate a script that automates a browser task (e.g., logging into a website and downloading a report).

Explanation: Selenium is used for browser automation. This prompt specifies the steps, wait conditions, and error handling.

Prompt text:

Write a Python script using Selenium that:
- Opens Chrome browser.
- Navigates to 'https://example.com/login'.
- Fills in username 'admin' and password 'password123' (use environment variables for real use).
- Clicks the login button.
- Waits for the dashboard to load (up to 10 seconds).
- Clicks the 'Download Report' button.
- Saves the downloaded file to './reports/'.
- Closes the browser.
- Uses WebDriverWait for synchronization.

Usage example: Run the script to automate weekly report downloads without manual intervention.

Best Practices for Writing Prompts for Python Code

  • Be specific about inputs and outputs: State file names, data types, and formats.
  • Specify libraries and versions: For example, "use pandas 2.0+" or "use Python 3.11+".
  • Include error handling: Ask for try-except blocks for file I/O, network calls, or database connections.
  • Define edge cases: Mention empty inputs, missing files, or invalid data.
  • Request comments and docstrings: This improves code readability and maintainability.
  • Iterate: If the first output isn't perfect, refine the prompt by adding constraints.

Conclusion

Prompt engineering for Python code generation is a skill that combines domain knowledge with clear communication. The ten prompts in this article cover common tasks from basic scripting to advanced FastAPI development, each designed to produce production-quality code with minimal iteration. By using these prompts as templates, you can save hours of manual coding and reduce debugging time. Start with the CSV parsing script for simple data tasks, then move to FastAPI endpoints for building APIs. Remember to always review and test AI-generated code—especially for security and performance—before deploying it. Happy coding!

← All posts

Comments