Last month, I had to build a dozen API endpoints for a new microservice. I knew the patterns – CRUD operations, SQLAlchemy models, Pydantic schemas – but typing out all that boilerplate felt soul-crushing.
I turned to AI, hoping it would save me hours. What followed was a rollercoaster of bad outputs, hallucinations, and frustration. But after a week of failed attempts, I found a prompting approach that actually produced reliable, copy-pasteable code.
This isn't a “just use this tool” story. It's about the technique that finally worked for me, with real examples you can adapt.
I started with the obvious: “Write a Flask route for creating a user.” The AI spat back something like:
@app.route('/users', methods=['POST'])
def create_user():
data = request.json
return jsonify({'id': 1, 'username': 'john'})
Hardcoded response! Not even using the input. I tried again: “Write a proper endpoint with validation.” It gave me a mix of Flask and FastAPI syntax. Maddening.
I realized the problem was me. I was asking AI to read my mind. It didn't know my database schema, error handling patterns, or even which ORM I used.
I tried several things that made things worse:
I stopped treating the AI like a senior developer and started treating it like a diligent intern who needs extremely detailed instructions. The key was to provide:
Here's the actual approach that clicked for me.
I built a prompt generator in Python. It takes a schema description and produces a prompt with examples:
import requests
def generate_endpoint_code(schema_json: dict) -> str:
system_msg = "You are a Python backend developer. You write Flask routes with SQLAlchemy and Marshmallow. Always include error handling and docstrings."
examples = [
{
"input": '{"model": "Project", "fields": ["id", "name", "created_at"]}',
"output": '''
from flask import Blueprint, request, jsonify
from models import db, Project
from schemas import ProjectSchema
projects_bp = Blueprint('projects', __name__)
@projects_bp.route('/projects', methods=['POST'])
def create_project():
schema = ProjectSchema()
try:
data = schema.load(request.json)
except ValidationError as err:
return jsonify(err.messages), 400
project = Project(**data)
db.session.add(project)
db.session.commit()
return jsonify(schema.dump(project)), 201
'''
}
]
user_prompt = f"""
Generate a Flask endpoint for creating a resource based on the following schema:
{schema_json}
Use the same style as the examples below.
Here is an example:
Example input:
{examples[0]['input']}
Example output:
{examples[0]['output']}
Now generate for this input:
{schema_json}
"""
response = requests.post(
"https://api.openai.com/v1/chat/completions",
headers={"Authorization": "Bearer YOUR_KEY"},
json={
"model": "gpt-4",
"messages": [
{"role": "system", "content": system_msg},
{"role": "user", "content": user_prompt}
],
"temperature": 0.2 # low creativity for deterministic output
}
)
return response.json()['choices'][0]['message']['content']
After this change, the AI started generating code that:
request.json
I could then copy the output directly into my project, only tweaking a few details.
This approach isn't magic. Here's what I wish someone had told me:
from sqlalchemy import Column, Integer, String
that was fine, but it once invented a from flask_sqlalchemy import db
that doesn't exist without extension setup. datamodel-code-generator
for Pydantic models and only use AI for the wiring (routes, error handling).AI code generation can save you from burnout on boilerplate, but it's not a silver bullet. The trick is to give the model the right amount of structure – not too vague, not too rigid. Embrace few-shot prompting. And always, always review the output.
I'm still early in this journey. How do you handle AI-generated code in your workflow? Do you rely on prompts, or have you built a custom tool around it? I'd love to hear what works for you.