DEV Community

megharrison92
megharrison92

Posted on

Vanilla Flask vs. RESTful Flask

Flask is a popular framework in Python that developers use to build applications and APIs. There are two different ways to go about it- you can use either "Vanilla Flask" or "RESTful Flask" (it could also be called Flask-RESTful).

Vanilla Flask
Vanilla Flask is the traditional way of building APIs, where you manually define the routes, handle HTTP methods, and manage data. While the setup is slightly more involved, it has the added benefit of being more flexible.

If you wanted to create an API to manage a list of books using Vanilla Flask it could potentially look like this-

from flask import Flask, jsonify

app = Flask(__name__)

books = [
    {"id": 1, "title": "Harry Potter", "author": "J.K. Rowling"},
    {"id": 2, "title": "The Hobbit", "author": "J.R.R. Tolkien"}
]

@app.route('/api/books', methods=['GET'])
def get_books():
    return jsonify(books)

if __name__ == '__main__':
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

RESTful Flask
RESTful Flask, which is sometimes referred to as Flask-RESTful, is an extension of Flask that has a more structured way of building APIs. It uses concepts like resources and HTTP methods as class methods, which simplify the process of creating APIs.

And if you wanted to create an API to manage a list of books using RESTful Flask it could potentially look like this-

from flask import Flask
from flask_restful import Api, Resource

app = Flask(__name__)
api = Api(app)

books = [
    {"id": 1, "title": "Harry Potter", "author": "J.K. Rowling"},
    {"id": 2, "title": "The Hobbit", "author": "J.R.R. Tolkien"}
]

class BookList(Resource):
    def get(self):
        return books

api.add_resource(BookList, '/api/books')

if __name__ == '__main__':
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)