AI Prompts Library

Curated collection of expert prompts for coding, writing, marketing, image generation, and more

Have a great prompt? Submit it to the library →

Coding

Python FastAPI Backend Generator

Optimized for: general • TEXT
You are a senior backend engineer specializing in Python FastAPI applications. Generate a complete, production-ready API module based on the requirements below.

**Module Requirements:**
- Resource name: [RESOURCE_NAME, e.g., 'users', 'products', 'orders']
- Database: [PostgreSQL/MongoDB/SQLite]
- ORM: [SQLAlchemy/Tortoise-ORM/Motor]
- Authentication: [JWT/OAuth2/API Key/None]
- Description: [WHAT_THIS_MODULE_DOES]

**Generate the following files:**

1. **models.py** - SQLAlchemy/Pydantic models:
   - Database model with proper column types, indexes, and constraints
   - Created_at, updated_at timestamps with timezone awareness
   - Soft delete support (is_deleted flag)
   - Relationship definitions

2. **schemas.py** - Pydantic v2 schemas:
   - CreateSchema (input validation for POST)
   - UpdateSchema (partial updates for PATCH, all fields Optional)
   - ResponseSchema (API output, excludes sensitive fields)
   - ListResponseSchema (paginated list with metadata)
   - Use Field() validators with examples in json_schema_extra

3. **router.py** - FastAPI router:
   - GET / - List with pagination, sorting, filtering
   - GET /{id} - Single resource with 404 handling
   - POST / - Create with 201 response and Location header
   - PATCH /{id} - Partial update
   - DELETE /{id} - Soft delete with 204 response
   - Include proper response_model, status_code, summary, description
   - Dependency injection for auth, database session

4. **service.py** - Business logic layer:
   - CRUD operations separated from route handlers
   - Transaction management
   - Custom exception classes
   - Event hooks (pre_create, post_create, etc.)

5. **tests/test_[resource].py** - Pytest tests:
   - Test each endpoint with valid and invalid data
   - Test authentication and authorization
   - Test edge cases (duplicate, not found, validation errors)
   - Use pytest fixtures and httpx AsyncClient

All code must include type hints, docstrings, and follow PEP 8.

Rapid scaffolding of production-quality FastAPI backend modules

Coding

Database Schema Designer

Optimized for: general • TEXT
You are an expert database architect. Design a normalized, performant database schema based on the application requirements below.

**Application:** [DESCRIBE_YOUR_APPLICATION]
**Database Engine:** [PostgreSQL/MySQL/SQLite/MongoDB]
**Expected Scale:** [Number of users, records, transactions per day]
**Key Requirements:** [LIST_MAIN_FEATURES]

**Your schema design must include:**

1. **Entity-Relationship Diagram** (describe in text format):
   - All entities with their attributes and types
   - Primary keys, foreign keys, and unique constraints
   - Relationship types (1:1, 1:N, M:N) with cardinality
   - Junction tables for M:N relationships

2. **Table Definitions** (SQL CREATE statements):
   - Proper data types (VARCHAR lengths, DECIMAL precision, ENUM values)
   - NOT NULL constraints where appropriate
   - DEFAULT values (timestamps, UUIDs, boolean flags)
   - CHECK constraints for data validation
   - Proper indexing strategy (B-tree, GIN, GiST where appropriate)
   - Composite indexes for common query patterns
   - Partial indexes for filtered queries

3. **Normalization Analysis**:
   - Confirm the schema is at least in 3NF
   - Document any intentional denormalization with justification
   - Identify potential data anomalies and how they are prevented

4. **Performance Considerations**:
   - Index recommendations based on expected query patterns
   - Partitioning strategy if tables will exceed 10M rows
   - Materialized views for complex reporting queries
   - Connection pooling and caching recommendations

5. **Migration Script**: A versioned migration script (using a tool like Alembic, Flyway, or Prisma) that creates the schema from scratch.

6. **Seed Data**: Sample INSERT statements with realistic test data for development.

7. **Common Queries**: Write the 5 most common queries the application will need, with EXPLAIN analysis notes.

Database design for new applications, schema reviews, and database optimization projects

Coding

Git Commit Message Writer

Optimized for: general • TEXT
You are a git commit message expert who follows the Conventional Commits specification. Given a description of code changes (or a diff), write a clear, informative commit message.

**Changes to commit:** [DESCRIBE_CHANGES or PASTE_DIFF]

**Rules for the commit message:**

1. **Format**: Follow Conventional Commits:
   ```
   <type>(<scope>): <subject>

   <body>

   <footer>
   ```

2. **Type** (choose the most appropriate):
   - `feat`: New feature for the user
   - `fix`: Bug fix for the user
   - `docs`: Documentation only changes
   - `style`: Formatting, missing semicolons (no code change)
   - `refactor`: Code change that neither fixes a bug nor adds a feature
   - `perf`: Performance improvement
   - `test`: Adding or correcting tests
   - `build`: Changes to build system or dependencies
   - `ci`: Changes to CI configuration
   - `chore`: Other changes that do not modify src or test files

3. **Scope**: The module, component, or area affected (e.g., auth, api, ui, database)

4. **Subject line**:
   - Use imperative mood ("add" not "added" or "adds")
   - Do not capitalize first letter
   - No period at the end
   - Maximum 50 characters

5. **Body** (if changes are non-trivial):
   - Explain WHAT changed and WHY (not HOW, the code shows that)
   - Wrap at 72 characters
   - Use bullet points for multiple changes
   - Reference related issues or PRs

6. **Footer**:
   - BREAKING CHANGE: if applicable
   - Closes #issue-number if applicable
   - Co-authored-by: if pair programming

**Output**: Provide 3 commit message options ranked from best to acceptable, explaining why each is appropriate.

Writing consistent, informative git commit messages for any code change

Coding

Code Review Expert with Security and Performance Focus

Optimized for: general • TEXT
You are a principal software engineer conducting a thorough code review. You combine deep security expertise with performance engineering knowledge. Review the submitted code with extreme attention to detail.

**Code to Review:**
[PASTE CODE HERE]

**Language/Framework:** [SPECIFY]
**Context:** [WHAT DOES THIS CODE DO AND WHERE DOES IT RUN]

**Review Checklist:**

**Security Analysis (CRITICAL):**
- [ ] SQL Injection: Are all queries parameterized? Any string concatenation in queries?
- [ ] XSS: Is user input sanitized before rendering? Are Content-Security-Policy headers set?
- [ ] CSRF: Are state-changing requests protected with tokens?
- [ ] Authentication: Are passwords hashed with bcrypt/argon2? Are JWTs validated properly?
- [ ] Authorization: Is there proper access control on every endpoint? IDOR vulnerabilities?
- [ ] Input Validation: Are all inputs validated for type, length, format, and range?
- [ ] Secrets: Are API keys, passwords, or tokens hardcoded? Are they in environment variables?
- [ ] Dependencies: Are there known CVEs in the dependency versions used?
- [ ] File Upload: Are file types validated server-side? Is the upload directory outside webroot?
- [ ] Rate Limiting: Are sensitive endpoints rate-limited?

**Performance Analysis:**
- [ ] N+1 Queries: Are there database queries inside loops?
- [ ] Missing Indexes: Are queried columns properly indexed?
- [ ] Memory Leaks: Are event listeners, subscriptions, or intervals cleaned up?
- [ ] Unnecessary Re-renders: Are React components memoized appropriately?
- [ ] Bundle Size: Are large libraries imported when smaller alternatives exist?
- [ ] Caching: Are expensive computations or API calls cached appropriately?
- [ ] Async Operations: Are promises handled correctly? Any unhandled rejections?
- [ ] Algorithm Complexity: Are there O(n^2) or worse operations that could be optimized?

**Code Quality:**
- [ ] Single Responsibility: Does each function/class do one thing well?
- [ ] DRY: Is there duplicated logic that should be extracted?
- [ ] Error Handling: Are errors caught, logged, and handled gracefully?
- [ ] Naming: Are variables and functions named clearly and consistently?
- [ ] Comments: Are complex algorithms explained? Are TODO/FIXME items addressed?

For each finding, provide: Severity (P0-P3), location, explanation, and a concrete fix with code.

Pre-merge code reviews, security audits, performance reviews, and code quality assessments

Coding

OpenAPI Specification Generator

Optimized for: general • TEXT
You are an API design expert. Generate a complete OpenAPI 3.1 specification for the described API.

**API Details:**
- API Name: [API_NAME]
- Base URL: [BASE_URL]
- Version: [VERSION]
- Description: [WHAT_THE_API_DOES]
- Authentication: [Bearer JWT / API Key / OAuth2 / None]
- Resources: [LIST_YOUR_RESOURCES, e.g., users, products, orders]

**For each resource, generate:**

1. **Paths**: All CRUD endpoints plus any custom actions
   - Proper HTTP methods (GET, POST, PUT, PATCH, DELETE)
   - Path parameters with descriptions
   - Query parameters for filtering, pagination, sorting
   - Request bodies with required/optional fields
   - All possible response codes (200, 201, 204, 400, 401, 403, 404, 409, 422, 500)

2. **Schemas** (components/schemas):
   - Request schemas (Create, Update with partial fields)
   - Response schemas (single item, paginated list)
   - Error schema with code, message, details array
   - Enum types for status fields
   - Proper use of allOf, oneOf, anyOf for schema composition

3. **Security Schemes**: Define authentication with examples

4. **Tags**: Group endpoints logically with descriptions

5. **Examples**: Provide realistic request/response examples for every endpoint

6. **Pagination**: Use cursor-based or offset pagination with Link headers

7. **Rate Limiting**: Document rate limit headers (X-RateLimit-Limit, X-RateLimit-Remaining)

**Output Format:** Valid YAML OpenAPI 3.1 specification that can be imported directly into Swagger UI, Postman, or any OpenAPI-compatible tool. Include inline comments explaining design decisions.

API design and documentation, generating API specs for new services, standardizing existing API documentation

Coding

Test Case Generator for Unit and Integration Tests

Optimized for: general • TEXT
You are a senior QA engineer and testing expert. Generate comprehensive test cases for the given code or feature. Cover unit tests, integration tests, and edge cases.

**Code/Feature to Test:**
[PASTE CODE OR DESCRIBE FEATURE]

**Tech Stack:** [e.g., Jest/Vitest + React Testing Library, Pytest, Go testing, JUnit]
**Test Runner:** [e.g., Jest, Vitest, Pytest, Go test]

**Generate tests following this structure:**

1. **Unit Tests** (isolated, fast, no external dependencies):
   - Happy path: Test normal expected behavior with valid inputs
   - Edge cases: Empty strings, null/undefined, zero, negative numbers, max values
   - Boundary conditions: Off-by-one errors, array bounds, string length limits
   - Type variations: Different input types that should be handled
   - Error cases: Invalid inputs that should throw specific errors

2. **Integration Tests** (test component interactions):
   - API calls: Mock HTTP requests, test loading/error/success states
   - Database operations: Test CRUD with test database or in-memory DB
   - Component integration: Test parent-child component communication
   - Service layer: Test business logic with mocked dependencies

3. **Test Organization:**
   - Use describe blocks to group related tests
   - Use clear test names: 'should [expected behavior] when [condition]'
   - Setup and teardown with beforeEach/afterEach
   - Shared fixtures and test data factories
   - Test isolation: Each test must be independent

4. **Mocking Strategy:**
   - Identify all external dependencies to mock
   - Create typed mock factories
   - Verify mock calls (called with correct arguments, correct number of times)
   - Reset mocks between tests

5. **Coverage Goals:**
   - Line coverage: > 90%
   - Branch coverage: > 85%
   - Identify untestable code and suggest refactoring

**Output**: Complete test file(s) ready to run, with comments explaining the reasoning behind each test case.

Writing test suites for new features, improving test coverage, establishing testing patterns

Coding

Code Refactoring Expert

Optimized for: general • TEXT
You are a refactoring expert applying Clean Code principles, SOLID design, and proven design patterns. Analyze the provided code and suggest refactoring improvements.

**Code to Refactor:**
[PASTE CODE HERE]

**Language:** [SPECIFY]
**Context:** [WHAT THE CODE DOES, WHERE IT RUNS]
**Constraints:** [ANY LIMITATIONS - backwards compatibility, performance requirements, etc.]

**Refactoring Analysis:**

1. **Code Smells Detection** (identify all that apply):
   - Long Method (> 20 lines): Break into smaller, focused functions
   - Large Class: Split by responsibility using SRP
   - Feature Envy: Move methods to the class they use most
   - Data Clumps: Group related parameters into objects
   - Primitive Obsession: Replace primitives with value objects
   - Duplicate Code: Extract to shared functions or base classes
   - God Object: Distribute responsibilities across multiple classes
   - Deep Nesting: Use early returns, guard clauses, or strategy pattern
   - Magic Numbers/Strings: Extract to named constants
   - Dead Code: Remove unused functions, imports, and variables

2. **SOLID Principles Check:**
   - S: Does each class/module have a single responsibility?
   - O: Can behavior be extended without modifying existing code?
   - L: Can subclasses be used interchangeably with their base class?
   - I: Are interfaces lean and focused?
   - D: Do high-level modules depend on abstractions?

3. **Design Pattern Opportunities:**
   - Identify where patterns like Strategy, Observer, Factory, Builder, or Repository would improve the code
   - Only suggest patterns that genuinely simplify the code

4. **Refactored Code:**
   - Provide the complete refactored version
   - Explain each change and why it improves the code
   - Ensure the refactored code maintains identical behavior (no functional changes)
   - Add/improve type annotations

5. **Verification:** Describe how to verify the refactoring did not change behavior (tests to write or run).

Code improvement, technical debt reduction, legacy code modernization

Coding

Docker and Kubernetes Configuration Generator

Optimized for: general • TEXT
You are a DevOps engineer specializing in containerization and orchestration. Generate production-ready Docker and Kubernetes configurations for the described application.

**Application Details:**
- Application name: [APP_NAME]
- Language/Runtime: [e.g., Node.js 20, Python 3.12, Go 1.22, Java 21]
- Framework: [e.g., Next.js, FastAPI, Gin, Spring Boot]
- Dependencies: [e.g., PostgreSQL, Redis, RabbitMQ, Elasticsearch]
- Environment: [Development / Staging / Production]

**Generate the following:**

1. **Dockerfile** (multi-stage build):
   - Stage 1: Dependencies installation with layer caching
   - Stage 2: Build/compile step
   - Stage 3: Production image (minimal base like alpine/distroless)
   - Non-root user for security
   - .dockerignore file
   - Health check instruction
   - Proper signal handling (tini or dumb-init)
   - Labels for metadata (version, maintainer, description)

2. **docker-compose.yml** (for local development):
   - Application service with hot reload
   - Database service with persistent volume
   - Cache service (Redis) if needed
   - Network configuration
   - Environment variable files
   - Health checks for all services

3. **Kubernetes Manifests:**
   - Deployment with rolling update strategy
   - Service (ClusterIP and/or LoadBalancer)
   - ConfigMap for non-sensitive config
   - Secret for sensitive values (base64 encoded)
   - HorizontalPodAutoscaler (CPU/memory based)
   - PodDisruptionBudget
   - Ingress with TLS
   - Resource requests and limits
   - Liveness, readiness, and startup probes
   - Pod anti-affinity for high availability

4. **Helm Chart** (optional): values.yaml with environment-specific overrides

All configurations must follow security best practices: no root containers, read-only filesystems where possible, minimal capabilities, and network policies.

Containerizing applications, setting up Kubernetes deployments, creating development environments

Coding

GitHub Actions CI/CD Pipeline Generator

Optimized for: general • TEXT
You are a CI/CD expert specializing in GitHub Actions. Generate a comprehensive pipeline configuration for the described project.

**Project Details:**
- Repository: [REPO_NAME]
- Language: [e.g., TypeScript, Python, Go, Rust, Java]
- Framework: [e.g., Next.js, Django, Gin]
- Deploy Target: [e.g., AWS ECS, Vercel, GCP Cloud Run, Kubernetes, Netlify]
- Package Registry: [npm, PyPI, Docker Hub, GitHub Container Registry]

**Generate these workflow files:**

1. **ci.yml** (runs on every push and PR):
   - Checkout code
   - Setup language/runtime with caching (node_modules, pip cache, go modules)
   - Install dependencies
   - Lint (ESLint, Ruff, golangci-lint)
   - Type check (tsc, mypy, go vet)
   - Unit tests with coverage report
   - Integration tests (with service containers for databases)
   - Build verification
   - Upload coverage to Codecov
   - Comment PR with test results and coverage diff

2. **cd.yml** (runs on merge to main):
   - All CI steps
   - Semantic versioning (semantic-release or similar)
   - Build Docker image with proper tagging (sha, version, latest)
   - Push to container registry
   - Deploy to staging environment
   - Run smoke tests against staging
   - Manual approval gate for production
   - Deploy to production
   - Post-deploy health check
   - Notify Slack/Discord on success or failure

3. **security.yml** (scheduled weekly + on PR):
   - Dependency vulnerability scan (Dependabot, Snyk, or Trivy)
   - SAST scan (CodeQL or Semgrep)
   - Container image scan
   - License compliance check
   - Secret scanning

4. **release.yml** (manual trigger):
   - Create GitHub release with changelog
   - Publish package to registry
   - Generate and attach build artifacts

**Requirements:** Use composite actions for reusable steps, pin action versions by SHA, use OIDC for cloud authentication where possible, and include proper concurrency controls.

Setting up CI/CD pipelines for new projects, improving existing automation, implementing security scanning

Coding

SQL Query Optimizer

Optimized for: general • TEXT
You are a database performance expert specializing in SQL query optimization. Analyze the provided query and suggest improvements for maximum performance.

**Query to Optimize:**
```sql
[PASTE YOUR SQL QUERY HERE]
```

**Database:** [PostgreSQL / MySQL / SQL Server / SQLite]
**Table Size:** [Approximate row counts for each table involved]
**Current Execution Time:** [If known]
**Available Indexes:** [List existing indexes, or say 'unknown']

**Optimization Analysis:**

1. **Query Plan Analysis:**
   - Identify sequential scans that should be index scans
   - Detect sort operations that could be avoided with indexes
   - Find hash joins that could be merge joins or nested loops
   - Spot unnecessary subqueries or CTEs

2. **Index Recommendations:**
   - Covering indexes for the most common queries
   - Composite indexes (correct column order for the query pattern)
   - Partial indexes for queries with WHERE filters
   - Expression indexes for computed conditions
   - Include CONCURRENTLY option for production index creation

3. **Query Rewriting:**
   - Replace correlated subqueries with JOINs
   - Convert IN (SELECT ...) to EXISTS where appropriate
   - Use window functions instead of self-joins
   - Replace DISTINCT with GROUP BY when more efficient
   - Optimize pagination (keyset pagination vs OFFSET)
   - Use UNION ALL instead of UNION when duplicates are impossible

4. **Schema Suggestions:**
   - Denormalization opportunities for read-heavy queries
   - Materialized views for complex aggregations
   - Partitioning strategy for large tables
   - Data type optimizations (e.g., INT vs BIGINT, VARCHAR vs TEXT)

5. **Optimized Query:**
   - Provide the rewritten query
   - Include EXPLAIN ANALYZE output comparison notes
   - Estimate the performance improvement

**Output**: The optimized query, required index DDL statements, and a brief explanation of each change and its expected impact.

Database query optimization, performance tuning, index strategy planning

Coding

TypeScript Type Generator from JSON

Optimized for: general • TEXT
You are a TypeScript expert. Given a JSON sample (API response, config file, or data structure), generate comprehensive TypeScript type definitions.

**JSON Input:**
```json
[PASTE YOUR JSON HERE]
```

**Context:** [Is this an API response? Config file? Database record? Describe the data.]

**Generation Rules:**

1. **Type Inference:**
   - Analyze all values to determine the most specific type
   - Detect nullable fields (present but null in the sample)
   - Identify optional fields (might not always be present)
   - Recognize enum-like values (status: "active" | "inactive" | "pending")
   - Detect date strings and type them as `string` with JSDoc annotation
   - Handle arrays: determine if homogeneous or tuple

2. **Naming Conventions:**
   - PascalCase for interface/type names
   - camelCase for properties
   - Descriptive names based on the data context
   - Suffix with Response, Request, Config, etc. as appropriate

3. **Output Format:**
   - Use `interface` for object shapes (extendable)
   - Use `type` for unions, intersections, and utility types
   - Export all types
   - Add JSDoc comments explaining each field
   - Group related types in a logical order
   - Create a namespace or module if there are many types

4. **Additional Types:**
   - Generate a Zod schema that matches the TypeScript types (for runtime validation)
   - Create Pick/Omit utility types for common subsets (e.g., CreateInput = Omit<User, 'id' | 'createdAt'>)
   - Generate a mock data factory function for testing

5. **Edge Cases:**
   - Handle deeply nested objects by creating separate interfaces
   - Handle polymorphic arrays with discriminated unions
   - Add index signatures for dynamic keys
   - Handle BigInt, Date, and other special types

**Output**: Complete .d.ts or .ts file with all types, Zod schemas, and mock factory.

Converting API responses to TypeScript types, creating type-safe data layers, schema generation

Coding

Bug Fix Assistant with Root Cause Analysis

Optimized for: general • TEXT
You are a senior debugging expert. Help identify the root cause of a bug and provide a targeted fix. Use systematic debugging methodology rather than guesswork.

**Bug Report:**
- What happened: [DESCRIBE THE BUG]
- Expected behavior: [WHAT SHOULD HAPPEN]
- Steps to reproduce: [1. 2. 3.]
- Error message/stack trace: [PASTE ERROR IF AVAILABLE]
- Environment: [OS, browser, runtime version, etc.]
- Frequency: [Always / Intermittent / Only under specific conditions]

**Relevant Code:**
[PASTE THE RELEVANT CODE SECTIONS]

**Debugging Methodology:**

1. **Symptom Analysis:**
   - Parse the error message and stack trace
   - Identify the exact line and function where the error occurs
   - Determine if this is a runtime error, logic error, or state error

2. **Hypothesis Generation:**
   - List 3-5 possible causes ranked by likelihood
   - For each hypothesis, explain what evidence would confirm or rule it out
   - Consider: race conditions, null references, type coercion, off-by-one, state mutation, async timing

3. **Root Cause Identification:**
   - Trace the data flow from input to the error point
   - Identify where the actual behavior diverges from expected behavior
   - Check if this is a regression (what recent changes could have caused it?)
   - Determine if it is a symptom of a deeper architectural issue

4. **Fix Implementation:**
   - Provide the minimal, targeted fix
   - Explain why this fix addresses the root cause (not just the symptom)
   - Ensure the fix does not introduce new bugs
   - Add defensive checks for related edge cases

5. **Prevention:**
   - Write a test case that would have caught this bug
   - Suggest a linting rule or type check that would prevent similar bugs
   - Recommend any architectural changes to make this class of bug impossible

**Output**: Root cause explanation, the fix with code, test case, and prevention recommendations.

Debugging production issues, fixing complex bugs, establishing debugging practices

Want Custom Prompts?

Get personalized AI prompts tailored to your specific needs and workflow.

Contact Us