Building JSON APIs
Building a complete REST API involves handling different HTTP methods, request data, and returning appropriate status codes. This chapter creates a CRUD API for blog posts.
GET – Retrieve All Posts
@app.route('/api/posts', methods=['GET'])
def get_posts():
posts = Post.query.all()
return jsonify([{'id': p.id, 'title': p.title, 'content': p.content} for p in posts])GET – Single Post by ID
@app.route('/api/posts/', methods=['GET'])
def get_post(post_id):
post = Post.query.get_or_404(post_id)
return jsonify({'id': post.id, 'title': post.title, 'content': post.content}) POST – Create New Post
@app.route('/api/posts', methods=['POST'])
def create_post():
data = request.get_json()
new_post = Post(title=data['title'], content=data['content'], author_id=current_user.id)
db.session.add(new_post)
db.session.commit()
return jsonify({'message': 'Post created'}), 201PUT – Update Post
@app.route('/api/posts/', methods=['PUT'])
def update_post(post_id):
post = Post.query.get_or_404(post_id)
data = request.get_json()
post.title = data.get('title', post.title)
post.content = data.get('content', post.content)
db.session.commit()
return jsonify({'message': 'Post updated'}) DELETE – Remove Post
@app.route('/api/posts/', methods=['DELETE'])
def delete_post(post_id):
post = Post.query.get_or_404(post_id)
db.session.delete(post)
db.session.commit()
return jsonify({'message': 'Post deleted'}) Two Minute Drill
- Use `request.get_json()` to parse JSON request body.
- Return status codes: 200 OK, 201 Created, 404 Not Found.
- Use `get_or_404()` for cleaner error handling.
- Test API with Postman or curl.
Need more clarification?
Drop us an email at career@quipoinfotech.com
