Building a REST Endpoint
Return JSON responses.
Building a REST Endpoint is a free Python Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What is a REST API?
A REST API exposes resources over HTTP using standard verbs. Instead of HTML pages, it returns data, usually as JSON, for other programs to consume.
from flask import Flask, jsonify
app = Flask(__name__)
# REST endpoints return data, not pages
print('REST APIs speak JSON over HTTP')Returning JSON
jsonify() turns a Python dict or list into a JSON response with the correct content type.
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/api/status')
def status():
return jsonify({'status': 'ok'})
print('jsonify builds a JSON response')Dicts Auto-Convert
Modern Flask also converts a returned dict to JSON automatically, so you can often skip jsonify().
from flask import Flask
app = Flask(__name__)
@app.route('/api/ping')
def ping():
return {'message': 'pong'}
print('Returning a dict yields JSON')Returning a List
To return a collection, pass a list to jsonify(). Each item is typically a dict representing one resource.
from flask import Flask, jsonify
app = Flask(__name__)
books = [{'id': 1, 'title': 'A'}, {'id': 2, 'title': 'B'}]
@app.route('/api/books')
def list_books():
return jsonify(books)
print('Return a list of resources')GET One Resource
Use a dynamic URL part to fetch a single item by id. Return 404 if it does not exist.
from flask import Flask, jsonify
app = Flask(__name__)
books = {1: {'id': 1, 'title': 'A'}}
@app.route('/api/books/<int:bid>')
def get_book(bid):
book = books.get(bid)
if book is None:
return jsonify({'error': 'not found'}), 404
return jsonify(book)
print('GET /api/books/1')Creating with POST
A POST request creates a resource. Read the JSON body, build the new item, and return it with status 201 Created.
from flask import Flask, request, jsonify
app = Flask(__name__)
books = []
@app.route('/api/books', methods=['POST'])
def create_book():
data = request.get_json()
book = {'id': len(books) + 1, 'title': data['title']}
books.append(book)
return jsonify(book), 201
print('POST creates and returns 201')Updating with PUT
PUT replaces or updates an existing resource identified by its id.
from flask import Flask, request, jsonify
app = Flask(__name__)
books = {1: {'id': 1, 'title': 'A'}}
@app.route('/api/books/<int:bid>', methods=['PUT'])
def update_book(bid):
if bid not in books:
return jsonify({'error': 'not found'}), 404
books[bid]['title'] = request.get_json()['title']
return jsonify(books[bid])
print('PUT updates a resource')Deleting with DELETE
DELETE removes a resource. Returning status 204 No Content is common on success.
from flask import Flask, jsonify
app = Flask(__name__)
books = {1: {'id': 1, 'title': 'A'}}
@app.route('/api/books/<int:bid>', methods=['DELETE'])
def delete_book(bid):
if bid in books:
del books[bid]
return '', 204
return jsonify({'error': 'not found'}), 404
print('DELETE removes a resource')Status Codes Matter
REST relies on HTTP status codes: 200 OK, 201 Created, 204 No Content, 400 Bad Request, 404 Not Found.
# 200 success
# 201 created
# 204 no content
# 400 bad request
# 404 not found
print('Use the right status code')Validating the Body
Check that required fields are present before creating. Return 400 with an error message when the body is invalid.
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/api/books', methods=['POST'])
def create_book():
data = request.get_json(silent=True) or {}
if 'title' not in data:
return jsonify({'error': 'title required'}), 400
return jsonify(data), 201
print('Validate JSON before using it')Consistent Responses
Good APIs return a predictable shape, often wrapping data and errors the same way every time so clients can rely on it.
from flask import jsonify
# Success: {'data': {...}}
# Error: {'error': 'message'}
# Keep the shape consistent across endpoints
print('Predictable shapes help clients')Quick Check
Test your REST knowledge.
Recap
You built a JSON REST endpoint.
jsonify()(or a returned dict) produces JSON responses- Map HTTP verbs: GET reads, POST creates, PUT updates, DELETE removes
- Return meaningful status codes like 201, 204, 400, 404
- Validate the request body and keep responses consistent
Frequently asked questions
Is the “Building a REST Endpoint” lesson free?
Yes — the full text of “Building a REST Endpoint” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.
What will I learn in “Building a REST Endpoint”?
Return JSON responses. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Python Academy?
No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Building a REST Endpoint” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Python Academy lesson?
Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Routes and Views
- Templates with Jinja2
- Forms and Request Data
- Building a REST Endpoint