We all struggle to make our world better, at least in the area we are competent at. And the GraphQL seems to be one of the most worth to notice inventions in a developer world.
In this article I will show you the benefits of GraphQL and present you a short working example. You can find a link to it at the end of the article.
It is important to mention, that GraphQL is not a type of magic tool or some programming language. It is just a description of easy and intuitive way to communicate between client app and backend. Yes, say farewell to tangled API’s, lots of entry-points, high entry-level for new developers, versioning mess, frustrating documentation, duplicating API calls and the feeling, that something could be undoubtedly much better here.
The GraphQL introduces us a brand new level of developers’ experience. Asking your server for a data has never been so easy and pleasant. GraphQL server can be written using any of modern programming languages. NodeJS, Ruby, Python, Scala, Java, Clojure, Go, PHP, C#, Elixir — all those programming languages already have GraphQL libraries, allowing you to build your own nice and robust GraphQL back-end.
How the GraphQL works?
Though it is easy as one-two-three for a new developer to understand and start working with GraphQL based API, it seems a bit challenging to create a GraphQL server that would work just the way you want. But this is due to lack of overall experience in this area. Just let some time to pass, and you will see this approach to back-end development will become a de-facto standard in apps development.
As it is stated here:
Graphs are powerful tools for modeling many real-world phenomena because they resemble our natural mental models and verbal descriptions of the underlying process.
There is already a lot of documentation and articles on GraphQL. You can get most of the information you need on http://graphql.org/. But before you start digging into it, let me shortly introduce you the principle of GraphQL.
The schema must be defined on the server side, where it states:
- which entities can be queried,
- which fields the entity should contain, and
- which relations we can have between the entities.
All requests to GraphQL server, which simply return data, are called “queries”. Those ones modifying data on server are called “mutations”.
For each field or a set of fields, a function, called “resolver” must be defined. This function is responsible for returning the required data. We can resolve a single field, as well, as a sub-entity, that gives us a perfect flexibility and clearance while retrieving necessary data from server.
A middle-ware function can be executed before each GraphQL call, where we can handle access rights logic. For instance, you can pass an auth token in each request’s header. Then in your middle-ware you read it and decide based on some access list, whether to give the requested information to the client or not.
Okay, seems interesting, how do I start?
Excellent dev tools, such as Graphiql and Apollo Client Developer tools already exist. They can make your life with GraphQL even better. There is an Apollo GraphQL Client, rich and flexible JS client, which can be used in modern web frameworks, such as ReactJS and Angular, as well as in vanilla JS. Apollo client also provides support for Android and iOS.
Here is a simple example of how to connect your DB data to GraphQL queries using graphene-sqlalchemy lib with relay specifications.
If you already have an existing sqlalchemy models of your database, you can connect them to GraphQL and make queries with a very little effort.
Please see the example for further info
This is our starting `filedemoapp.py` - https://github.com/maddevsio/graphql-demo/blob/master/demoapp.py
First we make necessary imports. Then we initiate Flask app, and within app context we initialize our config, import data model and graphql classes.
After that, we initialize `graphView` variable, which is a view function. We define view’s name, set schema, where we define our queries and mutations, set middle-ware and finally turn GraphiQL visual tool on.
Finally, we pass this variable to `app.add_url_rule()` , so that we bind our view to `/` route.
After that we define a `dbmodels.py` file, where we store our database models: https://github.com/maddevsio/graphql-demo/blob/master/dbmodels.py
Won’t tell about models much, those are standard sqlalchemy model declarations, except the moment, that models must be initialized using `declarative_base()`, bound to scoped database session. Yes, I am telling about those four rows after imports, where we, in some ridiculous way, combine database session with models :-)
Finally, we create `gqlmodels.py` file, where we state our GraphQL schema, bind GraphQL models to DB models and define allowed queries: https://github.com/maddevsio/graphql-demo/blob/master/gqlmodels.py
At the end of the file there is class Query. That is what we bind to the GraphQL schema and that is where we define fields allowed to be queried through GraphQL. A bit upper there, you see two models, correspondingly bound to BookModel and AuthorModel from previous `dbmodels.py`file.
Let’s check what we’ve got
Now if we run our app, we can already pass queries through GrafiQL interface. For instance, if we pass this query to: https://github.com/maddevsio/graphql-demo/blob/31b895b6ed540a24559b4c30bfb3f09e36b90fc6/requirements.txt
This strange query and also, those `nodes` and `edges` are coming from Facebook’s Relay.
Relay offers alternative approach to data pagination -Relay cursor connections which can be found as much more interesting pagination solution in some cases.
Okay, just let me touch it!
To see the GraphQL in action, you can `git clone` and run this example app from here:
Thanks for reading the article.