Creating a RESTful API using Flask?
Asked Answered
B

4

19

The Flask tutorial site here says that to create a RESTful API, you would write classes that extend restful.Resource, then add them to the API by:

app = Flask(__name__)
api = restful.Api(app)
class HelloWorld(restful.Resource):
    def get(self):
        return {'hello': 'world'}

api.add_resource(HelloWorld, '/')

However, I've looked at quite a few tutorials that all just use functions with the @app.route('/path') decorator that I'm more used to seeing in Flask apps. For example, here, they have:

@app.route('/todo/api/v1.0/tasks', methods=['GET'])
def get_tasks():
    return jsonify({'tasks': tasks})

And here:

@app.route('/')
def api_root():
    return 'Welcome'

What's the difference between using the restful.Resource class and just the decorated functions if any? If there are no differences, what should I be doing by convention to create a RESTful API?

Bismuthic answered 19/1, 2015 at 19:38 Comment(2)
restful.Resource originates from Flask extension. app.route is a solution based on pure Flask (and you can implement simple APIs very easily that way). After adding somethings like simple API exceptions this basic solution it is pretty much enough for simple APIs.Forney
@ujvl the link for the Flask Tuto is dead.Bromate
P
43

Short answer:

restful.Resource is from a Flask-Restful extension, which is not Flask itself. Miguel's tutorial uses Flask to write a restful interface.

Long answer:

First of all, along with Flask, there are a number of Flask extensions. Although they work together, they are separate packages and are written by individual authors. Flask-Restful is an extension to Flask.

Miguel's tutorial explains how you can make a restful api using Flask by itself.

Flask-Restful with the aim to saving some of us from re-inventing the wheel, promises to turn a custom class(or a custom Python data structure) to a restful web service. Flask-RESTX, a fork of Flask-Restful, auto-generates api documentation with swagger UI.

In addition, Flask also documented the usage of MethodView to allow developers to write their own restful APIs. In parallel, Flask-Restless promises to turn a SqlAlchemy class into a restful web service.

An update(18/07/2016), flask-api turns a function/view into a restful interface and is designed by Tom Christie, the author of django restful framework.

an update(17/03/2021), Flask-RESTPlus does smiliar things as above libraries but it also helps you construct swagger API documentation, which is an extra bonus.

There are many roads to Roma.

Pennington answered 20/1, 2015 at 13:41 Comment(0)
B
0

Using methods instead of classes can quickly become confusing when lots of endpoints are needed. Classes/resource are a better way of separating and decoupling logic. Plus your code becomes much more readable and easier to change/fix

Using flask-restful is probably the best way, although I will have some work to do in order to create the blueprint for your api, configuring routing, handling the request parameters, and many things that every normal api needs, that gets quite annoying.

I have built this lightweight framework on top of flask-restful that lets you build restful apis easily without worrying about all the wiring needed, and just focus on defining your api and coding the business logic. You can check it out here: https://github.com/sebastiandev/peach

It is more oriented to NOSQL databases, but thats only because the proxy for the database that comes as default is for mongodb, if you need sql, you can just make a proxy for sqlachemy (or wait until i find time to build it).

Berghoff answered 29/4, 2017 at 18:18 Comment(0)
N
0

I had the similar requirement posted in the question but instead had to retrieve with using the table object. Incase, if any one is looking for the solution, this might work.

from flask import Flask, request
import psycopg2 as pg
import os
from dotenv import load_dotenv

# load the environment information
load_dotenv()

app = Flask(__name__)
url = os.getenv('DATABASE_URL')
connection = pg.connect(url)

ALL_DISPOSITION_QUERY = "SELECT * FROM <tablename>; "

@app.route('/api/dispositions', methods=['GET'])
def get_all_dispositions():
    with connection:
        with connection.cursor() as cursor:
            cursor.execute(ALL_DISPOSITION_QUERY)
            rows = cursor.fetchall()
      return rows
Novgorod answered 13/5, 2023 at 11:6 Comment(0)
B
-1
#from flask import Flask

app = Flask(__name__)

@app.route('/')

def index():

    return "Hello, World!"

if __name__ == '__main__':

    app.run(debug=True)
Butene answered 5/2, 2019 at 18:45 Comment(1)
This has nothing to do with the question.Destructible

© 2022 - 2025 — McMap. All rights reserved.