sqlalchemy with graphql in python

To use SQLAlchemy with GraphQL in Python, we'll use Flask as our web framework and Graphene as our GraphQL library.

First, we need to install the required libraries:

main.py
pip install flask
pip install graphene
pip install sqlalchemy
62 chars
4 lines

Next, we'll create our Flask app and define our SQLAlchemy models. For this example, we'll create a simple model for a User:

main.py
from flask import Flask
from graphene import ObjectType, String, Int, Schema
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

app = Flask(__name__)

# Create database connection
engine = create_engine('sqlite:///example.db', echo=True)
Base = declarative_base()
Session = sessionmaker(bind=engine)

# Define User model
class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    email = Column(String)
    
# Create tables
Base.metadata.create_all(engine)
625 chars
23 lines

We also need to define our GraphQL schema, which will describe our API. We will create a UserType to represent the User object and a Query object to define our API's queries:

main.py
class UserType(ObjectType):
    id = Int()
    name = String()
    email = String()
    
class Query(ObjectType):
    users = String()

    def resolve_users(root, info):
        session = Session()
        users = session.query(User).all()
        ret = []
        for user in users:
            ret.append(UserType(
                id=user.id,
                name=user.name,
                email=user.email
            ))
        return ret
        
schema = Schema(query=Query)
483 chars
22 lines

Now we can start our Flask app and test our GraphQL API at http://localhost:5000/graphql. We can use GraphiQL, an in-browser IDE for exploring GraphQL APIs, to issue queries:

main.py
if __name__ == '__main__':
    app.run()

42 chars
4 lines
main.py
query {
  users {
    id
    name
    email
  }
}
50 chars
8 lines

This will return a list of users with their IDs, names and emails, stored in the SQLite database we defined. You can customize this query and define mutations to create, update and delete objects in the database with GraphQL.

gistlibby LogSnag