{"slug": "i-struggled-to-get-ai-to-write-useful-code-here-s-what-finally-worked", "title": "I Struggled to Get AI to Write Useful Code — Here's What Finally Worked", "summary": "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.", "body_md": "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.\n\nI 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.\n\nThis isn't a “just use this tool” story. It's about the technique that finally worked for me, with real examples you can adapt.\n\nI started with the obvious: “Write a Flask route for creating a user.” The AI spat back something like:\n\n``` python\n@app.route('/users', methods=['POST'])\ndef create_user():\n    data = request.json\n    # Create user logic\n    return jsonify({'id': 1, 'username': 'john'})\n```\n\nHardcoded 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.\n\nI 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.\n\nI tried several things that made things worse:\n\nI 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:\n\nHere's the actual approach that clicked for me.\n\nI built a prompt generator in Python. It takes a schema description and produces a prompt with examples:\n\n``` php\nimport requests\n\ndef generate_endpoint_code(schema_json: dict) -> str:\n    system_msg = \"You are a Python backend developer. You write Flask routes with SQLAlchemy and Marshmallow. Always include error handling and docstrings.\"\n\n    examples = [\n        {\n            \"input\": '{\"model\": \"Project\", \"fields\": [\"id\", \"name\", \"created_at\"]}',\n            \"output\": '''\n# routes/projects.py\nfrom flask import Blueprint, request, jsonify\nfrom models import db, Project\nfrom schemas import ProjectSchema\n\nprojects_bp = Blueprint('projects', __name__)\n\n@projects_bp.route('/projects', methods=['POST'])\ndef create_project():\n    schema = ProjectSchema()\n    try:\n        data = schema.load(request.json)\n    except ValidationError as err:\n        return jsonify(err.messages), 400\n    project = Project(**data)\n    db.session.add(project)\n    db.session.commit()\n    return jsonify(schema.dump(project)), 201\n'''\n        }\n    ]\n\n    # Build the prompt with examples + new request\n    user_prompt = f\"\"\"\nGenerate a Flask endpoint for creating a resource based on the following schema:\n{schema_json}\n\nUse the same style as the examples below.\nHere is an example:\n\nExample input:\n{examples[0]['input']}\n\nExample output:\n{examples[0]['output']}\n\nNow generate for this input:\n{schema_json}\n\"\"\"\n\n    response = requests.post(\n        \"https://api.openai.com/v1/chat/completions\",\n        headers={\"Authorization\": \"Bearer YOUR_KEY\"},\n        json={\n            \"model\": \"gpt-4\",\n            \"messages\": [\n                {\"role\": \"system\", \"content\": system_msg},\n                {\"role\": \"user\", \"content\": user_prompt}\n            ],\n            \"temperature\": 0.2  # low creativity for deterministic output\n        }\n    )\n    return response.json()['choices'][0]['message']['content']\n```\n\nAfter this change, the AI started generating code that:\n\n`request.json`\n\nI could then copy the output directly into my project, only tweaking a few details.\n\nThis approach isn't magic. Here's what I wish someone had told me:\n\n`from sqlalchemy import Column, Integer, String`\n\nthat was fine, but it once invented a `from flask_sqlalchemy import db`\n\nthat doesn't exist without extension setup. `datamodel-code-generator`\n\nfor 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.\n\nI'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.", "url": "https://wpnews.pro/news/i-struggled-to-get-ai-to-write-useful-code-here-s-what-finally-worked", "canonical_source": "https://dev.to/__c1b9e06dc90a7e0a676b/i-struggled-to-get-ai-to-write-useful-code-heres-what-finally-worked-432c", "published_at": "2026-06-03 08:01:28+00:00", "updated_at": "2026-06-03 08:12:51.663475+00:00", "lang": "en", "topics": ["artificial-intelligence", "large-language-models", "generative-ai", "ai-tools"], "entities": ["Flask", "FastAPI", "SQLAlchemy", "Pydantic", "Python"], "alternates": {"html": "https://wpnews.pro/news/i-struggled-to-get-ai-to-write-useful-code-here-s-what-finally-worked", "markdown": "https://wpnews.pro/news/i-struggled-to-get-ai-to-write-useful-code-here-s-what-finally-worked.md", "text": "https://wpnews.pro/news/i-struggled-to-get-ai-to-write-useful-code-here-s-what-finally-worked.txt", "jsonld": "https://wpnews.pro/news/i-struggled-to-get-ai-to-write-useful-code-here-s-what-finally-worked.jsonld"}}