Day 5 of 5
⏱ ~60 minutes
Flask in 5 Days — Day 5

REST API and Deploy

Build a JSON API with proper status codes, add CORS for frontend apps, and deploy to Render with gunicorn.

Building a JSON API

API views
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
CORS
pip install flask-cors

from flask_cors import CORS
CORS(app, resources={r'/api/*': {'origins': 'https://yourfrontend.com'}})
Deploy to Render
# 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-url
📝 Day 5 Exercise
Deploy Your Flask App
  1. A
  2. d
  3. d
  4. J
  5. S
  6. O
  7. N
  8. e
  9. n
  10. d
  11. p
  12. o
  13. i
  14. n
  15. t
  16. s
  17. f
  18. o
  19. r
  20. p
  21. o
  22. s
  23. t
  24. s
  25. (
  26. G
  27. E
  28. T
  29. l
  30. i
  31. s
  32. t
  33. ,
  34. G
  35. E
  36. T
  37. d
  38. e
  39. t
  40. a
  41. i
  42. l
  43. ,
  44. P
  45. O
  46. S
  47. T
  48. c
  49. r
  50. e
  51. a
  52. t
  53. e
  54. )
  55. .
  56. A
  57. d
  58. d
  59. C
  60. O
  61. R
  62. S
  63. .
  64. P
  65. u
  66. s
  67. h
  68. t
  69. o
  70. G
  71. i
  72. t
  73. H
  74. u
  75. b
  76. a
  77. n
  78. d
  79. d
  80. e
  81. p
  82. l
  83. o
  84. y
  85. t
  86. o
  87. R
  88. e
  89. n
  90. d
  91. e
  92. r
  93. .
  94. S
  95. e
  96. t
  97. e
  98. n
  99. v
  100. i
  101. r
  102. o
  103. n
  104. m
  105. e
  106. n
  107. t
  108. v
  109. a
  110. r
  111. i
  112. a
  113. b
  114. l
  115. e
  116. s
  117. i
  118. n
  119. t
  120. h
  121. e
  122. R
  123. e
  124. n
  125. d
  126. e
  127. r
  128. d
  129. a
  130. s
  131. h
  132. b
  133. o
  134. a
  135. r
  136. d
  137. .

Day 5 Summary

  • jsonify() converts Python dicts/lists to JSON responses with the correct Content-Type header.
  • Return proper status codes: 200 OK, 201 Created, 400 Bad Request, 404 Not Found, 401 Unauthorized.
  • Flask-CORS adds CORS headers. Restrict origins to your frontend domain in production.
  • gunicorn is the production WSGI server. gunicorn app:app = filename:flask_instance.
Finished this lesson?