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.py62 chars4 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.py625 chars23 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.py483 chars22 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.py42 chars4 lines
main.py50 chars8 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