Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Flask REST API Resourceful Blueprints Beyond GET and POST

Doesn't handle an incorrect ID/course with that ID doesn't exist

The put and delete methods that Kenneth Love creates don't account for the courses with the specified ID not existing.

Here's an alternative that uses the existing course_or_404 method he created (and the previous code commented out):

courses.py
    @marshal_with(course_fields)
    def put(self, id):
        args = self.reqparse.parse_args()
        query = models.Course.update(**args).where(models.Course.id == id)
        query.execute()
        #return (add_reviews(models.Course.get(models.Course.id == id)),
        return (add_reviews(course_or_404(id)),
                200,
                {'Location': url_for('resources.courses.course', id=id)})

    def delete(self, id):
        #query = models.Course.delete().where(models.Course.id == id)
        course_or_404(id).delete_instance()
        #query.execute()
        return '', 204, {'Location': url_for('resources.courses.courses')}

Also, I don't know if it was just with the code I was testing, but I think repeatedly sending the delete request when the ID didn't exist ended up just deleting everything. Note my use of the delete_instance() method instead of delete(), which is essentially for the whole table.

1 Answer

Oh and FYI Kenneth Love, passing catch_all_404s=True to the calls to Api() will return proper JSON encoded error responses for URLs like /api/v1/courses/bla:

courses.py
courses_api = Blueprint('resources.courses', __name__)
api = Api(courses_api, catch_all_404s=True)