Home »
AI Prompts Tutorial
AI Prompts for Code Generation
AI can help developers generate code for applications, scripts, functions, APIs, database operations, automation, testing, and many other programming tasks. A clear code generation prompt gives the AI model information about the programming language, requirements, expected behavior, and desired output.
In this chapter, you will learn 51 practical AI prompts for code generation. These prompts cover common development tasks, including generating functions, classes, APIs, database queries, frontend components, scripts, tests, and configuration files.
1. Generate a Simple Function
A function is one of the most common pieces of code developers need to create. AI can generate a function when you clearly describe its input, expected output, programming language, and special requirements.
Example
Write a Python function that accepts a list of integers
and returns the largest number.
Requirements:
- Handle an empty list.
- Use clear variable names.
- Include a short explanation.
- Provide two example inputs and outputs.
2. Generate a Class
AI can generate classes when the required properties, methods, and behavior are clearly defined. This can be useful when creating models, services, utilities, or object-oriented components.
Example
Create a Java class named Student.
Include:
- name
- rollNumber
- course
- marks
Add:
- Constructor
- Getter and setter methods
- A method to calculate the average marks
- A method to display student information
Use standard Java conventions.
3. Generate a Complete Program
AI can create a complete program when the problem and expected behavior are described clearly. Providing the required input, output, and constraints helps the model produce a more useful implementation.
Example
Write a Python program to calculate the factorial of a number.
Requirements:
- Read the number from the user.
- Handle zero correctly.
- Reject negative numbers.
- Display the result.
- Use clear and beginner-friendly code.
4. Generate a REST API
AI can generate the basic structure of a REST API when the endpoints, HTTP methods, request data, and expected responses are specified. You can also mention the framework you want to use.
Example
Create a REST API using Node.js and Express for managing users.
Endpoints:
GET /users
GET /users/:id
POST /users
PUT /users/:id
DELETE /users/:id
Use JSON requests and responses.
Include basic validation and error handling.
Explain the project structure.
5. Generate a CRUD Application
CRUD applications perform create, read, update, and delete operations on data. AI can generate the initial structure of a CRUD application when the technology stack and data model are provided.
Example
Create a CRUD application for managing products.
Technology:
- React
- Node.js
- Express
- MySQL
Product fields:
- id
- name
- price
- category
- stock
Generate the basic project structure and explain the main components.
6. Generate HTML Code
AI can create HTML structures for webpages based on the required sections and content. You can specify the semantic elements and layout you want to use.
Example
Create semantic HTML for a technology blog homepage.
Include:
- Header
- Navigation
- Main content
- Featured articles
- Categories
- Sidebar
- Footer
Use semantic HTML5 elements.
Do not add CSS or JavaScript.
7. Generate CSS Code
AI can generate CSS for page layouts, components, forms, navigation menus, cards, and responsive designs. Providing the HTML structure or describing the required visual layout helps produce more relevant CSS.
Example
Create responsive CSS for a blog card.
The card should contain:
- Image
- Title
- Description
- Author
- Date
Requirements:
- Clean modern design
- Responsive layout
- Rounded corners
- Subtle shadow
- Mobile-friendly spacing
8. Generate JavaScript Code
JavaScript can be generated for browser interactions, calculations, validation, API requests, and dynamic page behavior. Clearly describe the expected user interaction and output.
Example
Write JavaScript that validates a registration form.
Fields:
- Name
- Email
- Password
- Confirm password
Requirements:
- Check required fields.
- Validate email format.
- Check password length.
- Verify both passwords match.
- Display validation messages beside each field.
9. Generate React Components
AI can create reusable React components when the component's purpose, properties, state, and expected behavior are defined. This can speed up the creation of common user interface elements.
Example
Create a reusable React component named UserCard.
Props:
- name
- email
- profileImage
- role
Requirements:
- Use functional components.
- Use JSX.
- Display the information in a clean card.
- Make the component reusable.
- Include an example of how to use it.
10. Generate a Python Script
Python is commonly used for automation, data processing, file management, and scripting. AI can create scripts when the input, processing steps, and expected output are clearly defined.
Example
Write a Python script that reads all CSV files from a folder
and combines them into one CSV file.
Requirements:
- Use pandas.
- Handle files with the same columns.
- Skip empty files.
- Save the combined file as combined.csv.
- Include basic error handling.
11. Generate SQL Queries
AI can generate SQL queries when the database structure and desired result are provided. Mentioning the database system helps ensure that the query uses appropriate syntax.
Example
Write a MySQL query to find the top 10 customers
based on total purchase amount.
Tables:
customers(id, name)
orders(id, customer_id, amount)
Return:
- Customer ID
- Customer name
- Total purchase amount
Sort from highest to lowest.
12. Generate Database Tables
AI can generate SQL statements for creating database tables from a defined data model. You can specify columns, data types, primary keys, foreign keys, and constraints.
Example
Create a MySQL table named employees.
Columns:
- id: integer primary key
- name: string
- email: unique string
- department_id: integer
- salary: decimal
- joining_date: date
Add appropriate constraints and indexes.
13. Generate Database Schema
For larger applications, developers need relationships between multiple database tables. AI can create an initial schema based on the entities and relationships described in the prompt.
Example
Design a MySQL database schema for an online learning platform.
Entities:
- Students
- Instructors
- Courses
- Lessons
- Enrollments
- Reviews
Define:
- Tables
- Columns
- Primary keys
- Foreign keys
- Relationships
Also provide CREATE TABLE statements.
14. Generate Data Validation Code
Validation ensures that application input follows expected rules before it is processed. AI can generate validation logic for forms, APIs, configuration files, and other inputs.
Example
Write JavaScript validation code for a registration form.
Validate:
- Name is required.
- Email has a valid format.
- Password contains at least 8 characters.
- Confirm password matches the password.
Return clear validation messages.
15. Generate File Handling Code
Applications often need to read, write, upload, or process files. AI can generate file-handling code when the file type, programming language, and required operation are specified.
Example
Write a Python program that reads a text file
and counts the number of:
- Lines
- Words
- Characters
Handle the case where the file does not exist.
Display the results clearly.
16. Generate JSON Processing Code
JSON is widely used for APIs and data exchange. AI can generate code to parse, modify, validate, or transform JSON data.
Example
Write a Python program that reads a JSON file containing
a list of users.
For each user:
- Extract the name
- Extract the email
- Display the information
Handle invalid JSON and missing fields gracefully.
17. Generate API Integration Code
Applications frequently need to communicate with external APIs. AI can generate integration code when the API endpoint, HTTP method, request parameters, and response format are provided.
Example
Write Python code using the requests library to call this REST API:
Endpoint:
https://example.com/api/users
Method:
GET
Requirements:
- Send an authorization token in the header.
- Handle HTTP errors.
- Parse the JSON response.
- Print the user names.
18. Generate Authentication Code
AI can create a starting implementation for authentication workflows such as login and session handling. Authentication code should be carefully reviewed and tested before being used in a production environment.
Example
Create a basic user authentication example using
Node.js and Express.
Requirements:
- User registration
- User login
- Password hashing using an established password hashing library
- Session-based authentication
- Input validation
- Error handling
Explain the security considerations for production use.
19. Generate Unit Tests
Unit tests verify that individual functions or components behave as expected. AI can generate test cases when the source code and testing framework are provided.
Example
Write unit tests for this Python function using pytest.
Test:
- Normal input
- Empty input
- Negative values
- Boundary values
- Invalid input
[Paste function here]
20. Generate Integration Tests
Integration tests verify that multiple components work together correctly. AI can create test scenarios based on the services, APIs, database operations, or modules involved.
Example
Create integration tests for a REST API endpoint:
POST /api/users
Test:
- Valid user creation
- Missing required fields
- Duplicate email
- Invalid email
- Server error
Use Python and pytest.
Include setup and cleanup where necessary.
21. Generate Error Handling Code
Proper error handling helps applications respond predictably when something goes wrong. AI can create error-handling logic based on the expected failure conditions and programming language.
Example
Write a Python function that reads a number from user input.
Handle:
- Non-numeric input
- Empty input
- Negative numbers
- Unexpected errors
Return a clear message for each invalid case.
22. Generate Logging Code
Logging helps developers understand application behavior and investigate problems. AI can add structured logging to important operations while avoiding unnecessary or sensitive information in logs.
Example
Add Python logging to the following application.
Log:
- Application startup
- Successful operations
- Validation failures
- Exceptions
Use appropriate log levels.
Do not log passwords, tokens, or other sensitive information.
[Paste code here]
23. Generate Configuration Files
Modern applications often require configuration files for environments, dependencies, services, and deployment. AI can generate configuration files based on the technology and project requirements.
Example
Create a basic configuration file for a Node.js application.
Include configuration for:
- Application port
- Database connection
- Environment name
- Logging level
Use environment variables for sensitive values.
24. Generate Dockerfile
Dockerfiles define how an application is packaged into a container image. AI can create a starting Dockerfile based on the application's language, dependencies, port, and startup command.
Example
Create a Dockerfile for a Python Flask application.
Requirements:
- Use a suitable Python base image.
- Install dependencies from requirements.txt.
- Expose port 5000.
- Start the Flask application.
- Follow reasonable Docker practices.
Explain each major instruction.
25. Generate Docker Compose Configuration
Docker Compose can define multiple services that work together, such as an application, database, and cache. AI can generate a Compose file when the services and configuration requirements are provided.
Example
Create a Docker Compose configuration for:
Services:
- Node.js application
- MySQL database
Requirements:
- Application should connect to MySQL.
- Use environment variables for database credentials.
- Create a persistent database volume.
- Expose the application on port 3000.
26. Generate GitHub Actions Workflow
CI workflows can automatically build and test code whenever changes are pushed. AI can generate a GitHub Actions workflow based on the programming language and project's testing requirements.
Example
Create a GitHub Actions workflow for a Python project.
The workflow should:
- Run when code is pushed.
- Run for pull requests.
- Install dependencies.
- Run pytest.
- Report test failures.
Return the complete YAML file.
27. Generate Bash Scripts
Bash scripts can automate repetitive tasks on Linux and Unix-like systems. AI can generate scripts for file management, deployment, backups, and other administrative tasks.
Example
Write a Bash script that creates a backup of a specified directory.
Requirements:
- Accept the source directory as an argument.
- Create a timestamped backup.
- Store backups in a specified destination.
- Check whether the source directory exists.
- Display useful error messages.
28. Generate PowerShell Scripts
PowerShell can automate administration and development tasks on Windows systems. AI can create PowerShell scripts when the required operations and environment are described clearly.
Example
Write a PowerShell script that lists all files
larger than 100 MB in a specified directory.
Requirements:
- Accept the directory as an argument.
- Display file name and size.
- Sort results by file size.
- Handle an invalid directory.
29. Generate Regular Expressions
Regular expressions can be used for validation, searching, and extracting patterns from text. AI can create a regular expression based on examples and rules describing the expected pattern.
Example
Create a regular expression to validate a username.
Requirements:
- 5 to 20 characters
- Letters, numbers, and underscores only
- Must start with a letter
Provide:
- Regular expression
- Explanation
- Five valid examples
- Five invalid examples
30. Generate Data Processing Code
AI can create code that transforms, filters, sorts, groups, and aggregates data. Providing the input structure and expected output makes the generated solution more precise.
Example
Write Python code using pandas to process a CSV file.
Tasks:
- Remove duplicate rows.
- Handle missing values.
- Group records by category.
- Calculate the average price.
- Save the result to a new CSV file.
Explain the code briefly.
31. Generate Web Scraping Code
AI can generate code for collecting publicly accessible data when the website permits such access. The prompt should specify the target information and require respectful practices such as rate limiting and compliance with applicable website rules.
Example
Create a Python example using requests and BeautifulSoup
to parse publicly accessible HTML from a permitted website.
Extract:
- Article title
- Author
- Publication date
Requirements:
- Use a descriptive User-Agent.
- Add a reasonable delay between requests.
- Handle request errors.
- Do not bypass authentication or access controls.
32. Generate Pagination Code
Pagination is commonly used when an application needs to display a large number of records across multiple pages. AI can create pagination logic for frontend applications, APIs, or database queries.
Example
Create a Node.js Express API endpoint with pagination.
Endpoint:
GET /api/products
Query parameters:
page
limit
Return:
- Current page
- Page size
- Total records
- Total pages
- Product data
Include input validation.
33. Generate Search Functionality
Search functionality allows users to find relevant records based on keywords or filters. AI can create search logic when the data source, search fields, and expected behavior are clearly defined.
Example
Create a JavaScript function that searches a list of products.
Search across:
- Product name
- Category
- Description
Requirements:
- Ignore letter case.
- Return matching products.
- Return an empty array when there are no matches.
- Handle an empty search term.
34. Generate Sorting Code
Sorting allows applications to organize records according to a selected field or order. AI can create sorting functions for numbers, strings, dates, and other data types.
Example
Write a JavaScript function that sorts an array of users.
Allow sorting by:
- Name
- Age
- Registration date
Support:
- Ascending order
- Descending order
Do not modify the original array.
35. Generate Date and Time Code
Date and time operations often involve formatting, comparison, timezone handling, and calculations. AI can generate date-related code when the expected input and output formats are clearly specified.
Example
Write a Python function that accepts two dates
and calculates the number of days between them.
Requirements:
- Accept dates in YYYY-MM-DD format.
- Validate the input.
- Return the number of days.
- Handle invalid date formats.
36. Generate File Upload Code
File uploads are common in web applications and APIs. AI can generate an initial implementation based on the allowed file types, file size limits, storage location, and framework.
Example
Create a file upload endpoint using Node.js and Express.
Requirements:
- Accept image files.
- Allow JPG, PNG, and WebP.
- Limit file size to 5 MB.
- Validate the file type.
- Store files in an uploads directory.
- Return the uploaded file information.
Include basic error handling.
37. Generate Email Sending Code
Applications often need to send emails for notifications, verification, alerts, or business workflows. AI can generate email integration code when the provider, message structure, and requirements are specified.
Example
Create Python code to send an email using an SMTP server.
Requirements:
- Use environment variables for credentials.
- Accept recipient, subject, and message as parameters.
- Handle connection errors.
- Do not hardcode passwords or credentials.
Explain the configuration steps.
38. Generate Cache Implementation
Caching can reduce repeated processing and improve application performance. AI can create a basic caching implementation based on the application framework and cache technology.
Example
Create a simple Redis caching example for a Node.js application.
Requirements:
- Check the cache before querying the database.
- Store the result when it is not cached.
- Set an expiration time.
- Handle Redis connection errors.
Explain how the caching flow works.
39. Generate Queue Processing Code
Queues are useful for handling background tasks such as sending emails, processing files, and generating reports. AI can create queue-processing code when the task and queue technology are specified.
Example
Create a Python example using a task queue for processing
background email jobs.
Requirements:
- Add email tasks to a queue.
- Process jobs in the background.
- Handle failed jobs.
- Log task status.
- Keep credentials outside the source code.
40. Generate Code for Pagination in SQL
Database pagination can reduce the amount of data returned by a query. AI can create SQL pagination queries when the database system and table structure are provided.
Example
Write a PostgreSQL query to retrieve products using pagination.
Table:
products(id, name, price, category)
Parameters:
page
page_size
Return:
- Product records
- Total number of matching records
Sort results by id.
41. Generate Code Comments
Comments can make complex code easier for other developers to understand and maintain. AI can add useful comments while leaving the actual program logic unchanged.
Example
Add clear comments to the following Java code.
Requirements:
- Explain complex logic.
- Explain important calculations.
- Do not comment obvious lines.
- Do not change the code.
- Keep comments concise.
[Paste code here]
42. Generate Documentation From Code
AI can create documentation from existing source code by identifying functions, parameters, return values, exceptions, and usage examples. This can help developers create an initial documentation draft more quickly.
Example
Generate documentation for the following Python module.
Include:
- Module description
- Functions
- Parameters
- Return values
- Exceptions
- Usage examples
Use clear Markdown formatting.
[Paste code here]
43. Generate a README File
A README file explains what a project does and how developers can install and use it. AI can generate a README structure when the project details and available commands are provided.
Example
Create a README.md file for a Node.js REST API.
Include:
- Project description
- Features
- Requirements
- Installation
- Configuration
- Environment variables
- Running the application
- API endpoints
- Testing
- Project structure
Use clear Markdown headings.
44. Generate a Project Structure
A consistent project structure can make an application easier to maintain as it grows. AI can suggest folders and files based on the framework, architecture, and functionality of the project.
Example
Suggest a project structure for a Node.js and Express REST API.
The application should contain:
- Authentication
- Users
- Products
- Orders
- Database access
- Validation
- Error handling
- Tests
Show the folder and file structure.
Briefly explain the purpose of each major folder.
45. Generate Design Patterns
Design patterns provide reusable approaches for solving common software design problems. AI can generate an implementation of a selected pattern and explain how it fits the given use case.
Example
Implement the Factory Design Pattern in Java.
Create a practical example involving different types of
notifications such as:
- Email
- SMS
- Push notification
Explain the classes and how the factory works.
46. Generate Algorithms
AI can implement common algorithms when the desired input, output, constraints, and programming language are specified. It can also provide an explanation and complexity analysis.
Example
Implement binary search in Java.
Requirements:
- Accept a sorted integer array.
- Accept a target value.
- Return the index when the target is found.
- Return -1 when it is not found.
- Explain the algorithm.
- Provide time and space complexity.
47. Generate Data Structures
Developers can use AI to implement data structures such as stacks, queues, linked lists, trees, and graphs. Specifying the required operations helps ensure that the generated implementation matches the intended use.
Example
Implement a stack data structure in Python.
Support:
- push()
- pop()
- peek()
- is_empty()
- size()
Include error handling for pop and peek operations
when the stack is empty.
48. Generate Frontend Forms
AI can create HTML forms and related validation code based on the fields and behavior required by a webpage. You can specify the input types, validation rules, and desired structure.
Example
Create an HTML registration form.
Fields:
- Full name
- Email
- Password
- Confirm password
- Country
Requirements:
- Use semantic HTML.
- Add appropriate input types.
- Add labels.
- Mark required fields.
- Do not add CSS or JavaScript.
49. Generate Responsive UI Code
AI can create responsive frontend components that adapt to different screen sizes. Providing the required sections and responsive behavior helps the model generate a more appropriate layout.
Example
Create a responsive pricing section using HTML and CSS.
Include:
- Three pricing cards
- Plan name
- Price
- Features
- Call-to-action button
Requirements:
- Desktop: three columns.
- Mobile: one column.
- Use semantic HTML.
- Keep the CSS clean and easy to customize.
50. Generate Automation Code
Automation scripts can reduce repetitive development and operational work. AI can create automation code when the task, trigger, input, and expected result are clearly described.
Example
Write a Python script that checks a folder every hour
and moves CSV files older than seven days into an archive folder.
Requirements:
- Create the archive folder if it does not exist.
- Preserve the original file names.
- Log each moved file.
- Handle file access errors.
- Do not delete files.
51. Generate Code From Requirements
AI can turn detailed software requirements into an initial implementation. This approach is useful when the developer has a clear idea of what the application should do but needs help translating the requirements into code.
Example
Create a Python application based on the following requirements.
Application:
Task Management System
Features:
- Create tasks
- Update tasks
- Delete tasks
- Mark tasks as completed
- Search tasks
- Filter tasks by status
Requirements:
- Use object-oriented programming.
- Store tasks in a JSON file.
- Validate user input.
- Handle missing files.
- Separate the application logic into appropriate functions or classes.
- Include sample usage.
Provide the complete code and explain the project structure.
General AI Prompt Template for Code Generation
A reusable code generation prompt can help developers provide the AI model with the information needed to generate useful code. The template can be adapted for functions, applications, APIs, scripts, database queries, frontend components, and automation tasks.
Example
Role:
Act as a senior software developer.
Task:
[Describe what the code should do]
Programming Language:
[Language]
Framework or Technology:
[Framework, library, or technology]
Context:
[Describe the application or project]
Requirements:
- [Requirement 1]
- [Requirement 2]
- [Requirement 3]
Input:
[Describe the expected input]
Expected Output:
[Describe the expected output]
Constraints:
[Performance, compatibility, security, or other requirements]
Additional Instructions:
- Use clear and maintainable code.
- Handle relevant errors.
- Explain important implementation decisions.
- Include examples or tests where appropriate.
Advertisement
Advertisement