Building REST APIs with Flask-RESTful
While Flask can return JSON naturally, extensions like Flask-RESTful provide cleaner routing mechanisms and resource class structures for API design.
1 Class-Based Resource Mapping
Python — rest_api.py
from flask import Flask
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class UserResource(Resource):
def get(self, user_id):
return {"id": user_id, "username": "balaji"}
def put(self, user_id):
return {"updated": True}
api.add_resource(UserResource, "/users/<int:user_id>")
2 Code Challenge
Challenge: Extend the resource setup adding a
PostListResource that supports both GET (retrieving all posts) and POST (creating a new post) actions using validation arguments.