Search code examples
pythonflasksqlalchemygraphqlgraphene-python

Graphene/Flask/SQLAlchemy - What is the recommended method to retrieve data from a route entry point?


Given a basic project structure as follows:

/
 app.py     <-- Flask app startup and basic routing
 models.py 
 schema.py  <-- Contains Graphene/SQLAlchemy schema definitions for queries/mutations

Say in my app.py I have some basic routes setup like so:

@app.route('/members/list', methods=['GET'])
def members():
    # What should I do here?

What is the "correct" way to retrieve data? I can see a few different approaches, but I'm not sure if there's a recommended way and I can't seem to find a straightforward answer. For example:

  1. return jsonify(session.query(MembersModel).all()) I feel that this is probably the right way, but it feels weird plopping this down right at the route (feels like I'm missing some service layer architecture) or that I'm not using schema.py correctly. If I were to go this method, does this sit with in my schema.py? Or should I be making a different service-esque file elsewhere?

  2. Running a GraphQL query directly by myself like schema.execute('{ allMembers { ... } }') via Graphene (as seen here) and then parsing my result back in a response. This feels ... wrong, having hardcoded GraphQL in my code when there's a better alternative in #1.

I have prior experience with Spring and I always did it with an MVC styled controller <-> service <-> dao, but I'm not sure what the Flask/Graphene/SQLAlchemy/GraphQL/SQLite equivalent is. I have this nagging feeling that I'm missing an obvious answer here, so if anyone could direct me to some resources or help out, I'd appreciate it.

Thanks!


Solution

  • Okay, after hours of reading I finally realized it: I'm not supposed to be playing between REST web api's and GraphQL like this (disregarding legacy systems/migrations/etc). Essentially, GraphQL loosely competes with REST sort of in the vein with how JSON competes with XML.

    I was under the impression that GraphQL was comparable to a higher-level SQL, wherein GraphQL sat above my SQLite layer and abstracted away traditional SQL with some new-fangled terminology and abstractions like relays and connections. Instead, GraphQL competes at an even higher level as mentioned earlier.

    So, when dealing with Flask, GraphQL and Graphene, the most I should be doing is execute queries via the GraphiQL interface or POST'em to my server directly - and not do something like GET /my-path/some-resource just to manually hit a GraphQL query somewhere in the backend.

    Of course, if I misinterpreted anything, please let me know!