Build a JSON API with proper status codes, add CORS for frontend apps, and deploy to Render with gunicorn.
from flask import jsonify
@app.route('/api/posts', methods=['GET'])
def api_posts():
posts = Post.query.filter_by(published=True).all()
return jsonify([{'id': p.id, 'title': p.title, 'body': p.body} for p in posts])
@app.route('/api/posts/', methods=['GET'])
def api_post(id):
post = Post.query.get_or_404(id)
return jsonify({'id': post.id, 'title': post.title, 'body': post.body})
@app.route('/api/posts', methods=['POST'])
@login_required
def api_create_post():
data = request.get_json()
if not data or not data.get('title'):
return jsonify({'error': 'title required'}), 400
post = Post(title=data['title'], body=data.get('body',''), user_id=current_user.id)
db.session.add(post)
db.session.commit()
return jsonify({'id': post.id}), 201 pip install flask-cors
from flask_cors import CORS
CORS(app, resources={r'/api/*': {'origins': 'https://yourfrontend.com'}})# render.com → New Web Service → Connect GitHub
# Build command: pip install -r requirements.txt
# Start command: gunicorn app:app
# Add env vars: SECRET_KEY, DATABASE_URL
# requirements.txt
flask
flask-sqlalchemy
flask-migrate
gunicorn
psycopg2-binary
dj-database-urljsonify() converts Python dicts/lists to JSON responses with the correct Content-Type header.gunicorn app:app = filename:flask_instance.