cd /news/artificial-intelligence/i-struggled-to-get-ai-to-write-usefu… · home topics artificial-intelligence article
[ARTICLE · art-20130] src=dev.to pub= topic=artificial-intelligence verified=true sentiment=↑ positive

I Struggled to Get AI to Write Useful Code — Here's What Finally Worked

A developer struggling with unreliable AI-generated code for a microservice project built a Python prompt generator that produces detailed, structured prompts with examples, resulting in consistent, copy-pasteable Flask routes with SQLAlchemy and Marshmallow. The technique treats the AI like a diligent intern requiring explicit instructions, including system messages defining the tech stack and low-temperature settings for deterministic output. After implementing this approach, the developer was able to directly copy AI-generated endpoint code with minimal tweaks, saving hours of boilerplate work.

read3 min publishedJun 3, 2026

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.

── more in #artificial-intelligence 4 stories · sorted by recency
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
Live at https://your-agent.zahid.host
Get free account → Pricing
from €0/mo · no card required
LIVE [news/i-struggled-to-get-a…] indexed:0 read:3min 2026-06-03 ·