We're sorry but this page doesn't work properly without JavaScript enabled. Please enable it to continue.
Feedback

Getting a Grip on GraphQL

00:00

Formal Metadata

Title
Getting a Grip on GraphQL
Title of Series
Number of Parts
90
Author
License
CC Attribution 3.0 Unported:
You are free to use, adapt and copy, distribute and transmit the work or content in adapted or unchanged form for any legal purpose as long as the work is attributed to the author in the manner specified by the author or licensor.
Identifiers
Publisher
Release Date
Language

Content Metadata

Subject Area
Genre
Abstract
GraphQL is a query language for your API. This allows you to interact with your existing web services and databases in a new way. Instead of relying on a predetermined output structure from your API, you can “query” it and choose only the fields that you’re interested in. In this talk, learn what GraphQL is all about and how you can take advantage of it in your applications. A few key GraphQL terms we'll cover are: * Fields/Types * Variables * Queries/Mutations Then we'll take a look at how you can integrate the Apollo Client library inside of an Android application. GraphQL isn't going away, so here's your chance to get a grip on this exciting technology!
SubsetWebsiteComputer fileMassGoodness of fitMultiplication signTraffic reportingCartesian coordinate systemComputer animation
Cartesian coordinate systemClient (computing)Android (robot)ImplementationOrder (biology)Server (computing)Graph (mathematics)Computer clusterSoftware developerComputer animation
Query languageCASE <Informatik>ResultantQuery languageSoftware developerFile formatProgramming languageDatabaseFormal languageArithmetic meanSequelTerm (mathematics)Right angleForm (programming)Computer animation
Local ringShape (magazine)Query languageField (computer science)ImplementationElectronic mailing listState of matterShape (magazine)Object (grammar)Operator (mathematics)Client (computing)ResultantQuery languageCASE <Informatik>Graph (mathematics)WordPay televisionComputer animation
Patch (Unix)Dependent and independent variablesCategory of beingState of matterDatabaseBitPatch (Unix)PlanningTurtle graphicsQuery languageGraph (mathematics)CASE <Informatik>Electronic mailing listCustomer relationship managementObject (grammar)Logic gateShape (magazine)InformationField (computer science)Pairwise comparisonComputer animationDiagram
Graph (mathematics)Connected spaceDifferent (Kate Ryan album)Data structureOnline helpFacebookBlock (periodic table)Latent heatDomain nameBlogDiagram
Graph (mathematics)Formal languageQuery languageGamma functionMaizeExecution unitASCIIMaxima and minimaInclusion mapToken ringSimilarity (geometry)Operations researchArrow of timeLatent heatDifferent (Kate Ryan album)FacebookEntire functionFormal languageServer (computing)Client (computing)Graph (mathematics)ImplementationComputer animation
WeightJava appletAndroid (robot)Scripting languageImplementationServer (computing)Formal languageClient (computing)Computer animation
Query languageField (computer science)Object (grammar)Query languageResultantGraph (mathematics)Field (computer science)Electronic mailing listNumbering schemeFormal languageComputer animation
Field (computer science)Field (computer science)Electronic mailing listPower (physics)ResultantObject (grammar)Computer animation
Query languageLatent heatComputer-assisted translationCore dumpQuery languageElectronic mailing listPoint (geometry)Right angleBitShape (magazine)Computer animation
WindowTriangleRectangleElectronic meeting systemChi-squared distributionObject (grammar)Electronic mailing listQuicksortSign (mathematics)Right angleShape (magazine)Computer animation
Shape (magazine)RectangleObject (grammar)Multiplication signComputer animation
Query languageDependent and independent variablesShape (magazine)MultiplicationMultiplication signIntegrated development environmentField (computer science)Core dumpMereologyComputer animation
Field (computer science)Server (computing)MereologyCore dumpField (computer science)Graph (mathematics)Point (geometry)Server (computing)Computer animation
Single-precision floating-point formatQuery languageString (computer science)Parameter (computer programming)Query languageObject (grammar)Graph (mathematics)Multiplication signPoint (geometry)Category of beingComputer animation
Regular graphRepresentational state transferInheritance (object-oriented programming)Dependent and independent variablesQuery languageGraph (mathematics)Multiplication signPower (physics)Complex (psychology)Computer animation
Binary fileQuery languageVariable (mathematics)Multiplication signComplex (psychology)NumberSign (mathematics)Computer animation
Server (computing)BuildingSoftware frameworkType theorySoftware frameworkServer (computing)Service (economics)Hand fanGraph (mathematics)Type theoryResolvent formalismInjektivitätSocial classField (computer science)Scalar fieldArithmetic meanString (computer science)Object (grammar)Interior (topology)IntegerDatabaseCASE <Informatik>Network topologyInformationQuery languageResultantFormal languageScaling (geometry)WordChaos (cosmogony)Numbering schemeRight angleKey (cryptography)Physical systemCodeComputer animation
Query languageFormal languageFocus (optics)CodeField (computer science)Query languageBuildingType theoryServer (computing)Client (computing)Ideal (ethics)CASE <Informatik>Numbering schemeComputer animation
Graph (mathematics)Query languageDependent and independent variablesServer (computing)Type theoryField (computer science)Client (computing)CodeQuery languageResolvent formalismPower (physics)Functional (mathematics)Electronic mailing listArray data structureAbstractionDomain namePoint (geometry)Graph (mathematics)Interactive televisionAverageRow (database)Sign (mathematics)Instance (computer science)Source codeInformationDifferent (Kate Ryan album)DatabaseMultiplicationSoftware developerNumbering schemeComputer animation
Client (computing)Point (geometry)Server (computing)Resolvent formalismSoftware developerCartesian coordinate systemWeb 2.0Client (computing)Mobile appComputer animation
Shape (magazine)Point cloudSphereSource codeInformationSample (statistics)TriangleMobile appoutputServer (computing)Point (geometry)Computer architectureComputer fileGraph (mathematics)Numbering schemeINTEGRALClient (computing)ImplementationConnectivity (graph theory)Android (robot)Computer animation
ArchitectureSample (statistics)Computer fileClient (computing)ImplementationComputer architectureClient (computing)Computer fileINTEGRALServer (computing)Library (computing)Computer animation
Client (computing)Server (computing)Web browserCodeLibrary (computing)Computer animation
InformationProjective planeDesign by contractServer (computing)Computer fileMedical imagingData storage deviceLine (geometry)Client (computing)Numbering schemeComputer animation
Computer filePlug-in (computing)Computer fileRegular graphClient (computing)Query languageProcess (computing)Social classState of matterComputer animation
Computer fileElectric generatorPlug-in (computing)Social classServer (computing)Java appletProcess (computing)Computer animation
Variable (mathematics)Dependent and independent variablesString (computer science)Military operationDependent and independent variablesInformationCodeComputer animation
Computer fileMiniDiscPoint cloudInformationSource codeDependent and independent variablesQuery languageComputer fontBuildingElectronic mailing listDependent and independent variablesProcess (computing)Client (computing)Query languageObject (grammar)Server (computing)Order (biology)Thread (computing)Graph (mathematics)Row (database)Computer animation
MiniDiscShape (magazine)Point cloudSphereSource codeCodeOpen sourceServer (computing)Row (database)Ocean currentElectronic mailing listOrder (biology)Computer animation
Default (computer science)Server (computing)Graph (mathematics)Android (robot)Computer animation
Client (computing)Cone penetration testCustomer relationship managementContinuous integrationDiscrete element methodDatabaseBitGraph (mathematics)Client (computing)Computer animation
Graph (mathematics)DatabaseFormal languageNetwork topologyNumbering schemeBasis <Mathematik>InformationFormal languageCheat <Computerspiel>DatabaseImplementationGraph (mathematics)AbstractionBit rateDressing (medical)Interactive televisionComputer animationXML
Right angleProjective planeComputer animation
Computer animation
Transcript: English(auto-generated)
All around the world, there are UFO sightings. And some people choose to report these sightings, and then they're all collected together and stored in a massive CSV file. We're going to look at just a small subset of that data that starts at the beginning of 2013 and ends at the end of the following year.
What's interesting is that the United States has by far the most reported UFO sightings at a whopping 8,021. And this happens to be 891 times as many sightings as reported in Germany. So what's going on here?
Cloudy, good. And I thought to myself, with such an interesting data set, this would be a really cool way to dig into GraphQL, learn more about this technology and how we can use it to empower our applications. So here's today's agenda. We're gonna start by first looking at some of the basics,
the things that you absolutely need to understand in order to work with GraphQL. Next, we're gonna talk about GraphQL servers, what they're made up of, and how you can write one in Kotlin. And then finally, we're going to look at a GraphQL client. This is what we use to talk to our GraphQL server.
And since I'm an Android developer, we're going to look at an Android implementation. So let's get started with the basics. And we're gonna look at three things that GraphQL is and kinda is not. So first, GraphQL is a query language for your API.
Now what does that mean? When you first hear it, what is a query language in the first place? Right, this is any kind of programming language that can request information and get it back in a certain format. What is this? Okay, right, SQL for developers. This is SQL, structured query language.
There goes that phrase again. It's made up of certain keywords like select and from. These determine the kinda data that you're gonna get back as a result. Now in the case of SQL, it talks to a database, and then you might get back a list of names. We're gonna look at how this works out with GraphQL.
So for today's reference implementation, this is the data we're gonna be working with. It's a UFO sighting, and it has all these different fields so the date of the sighting, city, state, country, the shape of the sighting, all these things, comments, let alone. So this is an example of a GraphQL query, right?
It also contains keywords that determine the results. The first thing to note is the operation. In this case, it's a query, but there are other operations available like mutations as well as subscriptions. There's an operation name. This is used for debugging
as well as certain GraphQL clients take advantage of this name to generate data for you. Finally, this is the object or objects that you're interested in. In this case, we're saying, I wanna know about a list of UFO sightings. And then finally, on the inside are the fields. Specifically, I only want the ID
and the shape of a UFO sighting. So once you have a query like this, instead of talking to a database like in our SQL case, it's gonna talk to an API. And then once that's executed, we'll get back a response. So let's take a closer look at this. The first thing you'll notice is that it's simple JSON.
So it's something that we're all already familiar working with. And inside of a plain JSON object, there's a data property. And then that property contains the information that we're interested in, a list of UFO sightings. And specifically, only the fields that we requested, the ID and the shape.
Now let's say in your mind, you wanna compare GraphQL with REST. It will look a little bit like this. You would make a query in GraphQL and it's more like making a GET with REST. And a mutation is related to post-put-patch-delete. So when I first approached GraphQL and I heard mutation, I thought of like X-Men and Ninja Turtles,
but it really has nothing to do with that. It's about mutating or changing the state of your data. And it's really helpful to kinda keep this in your mind when you start working with GraphQL so you'll know which one to choose. Now, another thing about GraphQL is that it's related to your data being in a graph-like structure.
So if you have a blog, those blogs can have users. Users can write posts, posts can have comments, and then those comments can be written by users. So GraphQL helps support the way you actually structure your business domain in that you can have these connections
very easily queryable from your API. The next thing is GraphQL is a specification. So what do we mean by that? Facebook developed it. You can read the entire spec on facebook.github.io to learn about all the different pieces of GraphQL. But the most important thing is that this allows you
to use GraphQL in any language you like. So these are some various server implementations from C Sharp to Elixir, Kotlin, and more. And the same thing is true of your GraphQL clients. You can use any of these different languages to support your GraphQL client. The final thing that we wanna mention
as far as what GraphQL is is that it's introspective. This is not something that we use every day, but this basically means that using GraphQL language itself, you can find out about your GraphQL schema. So here's an example. You've already seen query, but now there's something new. There's this underscore underscore type,
and we're providing a name. This is how we're sending a query to GraphQL to find out about something in our schema. Specifically, we want the list of all the fields and their names. So if we were to run this query, we would see a result like this. The JSON object again, inside of data,
but then the fields and all of their names of our objects. What's powerful about this is that it supports the various tools to allow you to look at your API, understand what's going on, as well as debug issues. That's why when you hear people talk about GraphQL and the ability to perform introspection, they're so excited about it because it allows you
to do really cool things with tools. So just to recap, GraphQL is a query language, it's a specification, and it's introspective. And it does have other features, but these are the core things that make it really powerful. But so what? Like, okay, that's great, I'm really excited
to hear GraphQL can do all these things, but why would I consider using GraphQL over sticking with REST? Well, let's talk about REST a little bit, right? Let's say we wanted to get a list of UFO sightings. We would probably have some sort of UFO sightings endpoint, we'd make our request,
and then we'd get back the list of data. But if I only wanted the ID and the shape, I'm getting all this other data anyway. So it's very bloated, it's giving me back stuff that I do not need in my UI. Also, what if I needed to get more things from the API? I'd need not only a list of UFO sightings,
but I also want a list of the users who reported those things. I may have to make multiple requests to get that data. But GraphQL aims to fix all of those sort of challenges, right? So first, you only get what you asked for. In this example, I'm saying I want the UFO sighting
with this ID, and I just want the ID, the shape, and the country. And on the right-hand side, you see that's all I get back nothing extra, nothing that's not needed by my UI. Next, I can make multiple requests at the same time. So if I want to get some UFO sightings, and I want some other object, top country sightings,
I can just make one request inside of a query and get all the data back that's needed. So if you're working in maybe resource-constrained environments, you don't want to have to keep making multiple requests, GraphQL solves that problem for you. And finally, documentation is a core part of what makes GraphQL special.
You can easily see all of the fields that are available inside of your schema and navigate seamlessly between all of them. So with the basics under our belt, we can now move on to talk about the GraphQL server. Now the first thing to note is that there's a single endpoint, which is typically slash GraphQL,
that's used to handle all of your requests. And initially, you're thinking, hey, how can this one endpoint do all of this? Well, let's take a closer look. So first, you can make a HTTP GET request to that endpoint, and you would pass in your query parameter as a GraphQL query in a string.
It's really simple. You could also make a POST request, but this time, you would use a JSON object with a query property, and then you would pass in your query in that string. Now why is this super cool? How many people have used Postman before? Right, almost all of us.
It's like a really standard way to work with REST APIs. But you can do the same thing using GraphQL. Here, I have Postman, I have a GraphQL query, and I just execute it, and I get back that JSON data. So there's nothing super fancy about it. It's still regular HTTP requests.
Make a query, get back a response. Really cool. Now if we take, this is like a more complex example, but I'm still making a POST request where I have a query, but this time I have variables. So just slowly showing you how powerful GraphQL can be. I'm gonna get back the same exact response, but this time I have a variable way of providing
the number of UFO sightings that I'm interested in. So let's look at what went into building our UFO sightings GraphQL server. So the first thing is, I'm a big fan of Kotlin, so I said all right, if I'm gonna build a UFO sighting server, I'm gonna build it all in Kotlin.
So that's what I did. First, Ktor, server framework. Coin for dependency injection. Squash for database access. And then the star of the show is K GraphQL, because it's in Kotlin, so it starts with K obviously, for our GraphQL support. Now a GraphQL server consists of these three things,
types, schema, and resolvers. So we're gonna look at them one by one. And we're gonna start with the type system, right? So types just represent some kind of object that you can fetch from your server and what fields it has. So if we look at the case of a really simple UFO sighting, this is how we would define it.
It's type keyword, we give it a name, and then we specify the fields and their type. And what you'll notice here is that the ID is an integer but then it has the exclamation mark afterwards, which means that that thing cannot be nullable. And then finally, the city is just a plain string that can be nullable.
And int and string are both known as scalar types, meaning that that's the end of the query. We can't get any more information out of it. So if you were trying to go and say, all right, well, you have an ID, let me get some more data out of this thing. That would be totally wrong because that's not how GraphQL works. Scalars are basically the bottom leaves of your tree.
Now let's say we wanna represent this inside of K GraphQL in Kotlin. That's it. It's really nice. It's a really simple way to use Kotlin in GraphQL. We just specify our type and we have a data class. So that's it.
These two things are the same. So on the one hand is our code in Kotlin, and on the other hand is our GraphQL schema language. They're basically synonymous. Okay, so moving on to the next thing that connects all of your various types together, that's our schema. So let's focus on that. The schema is really simple.
You just have a query that's like the most basic example, and the query is a type where you specify the different fields. So in this case, UFO sighting based on an ID, and then we're back to our original type. So just like that, we see how it's building up. So the schema is the thing that allows the client
and the server to communicate with each other. It tells you what queries you're allowed to make, what are the type of those queries, and then what fields are available. So this is how we can build it up in Kotlin. We have that type once again, and then we have a query function that takes in a name that we're interested in.
So what you'll notice is something new that I haven't talked about yet. Resolver, that just came out of nowhere, so let's go ahead and cover that next. The resolver is the way that you map your business domain to your GraphQL types. So if we look at this instance, and someone says, hi, I'm interested in a UFO sighting
with this particular ID, we can look in our database, get the record, and send it back to the user. But we could also just have made a rest request to get the information and send it back to the user. The key thing here is that GraphQL abstracts away from your users where your data is coming from.
It doesn't matter, I could just have a huge array list full of UFO sightings, and I could send one to the user. They don't have to know. So that's the power of GraphQL. Just think about, you can get it from multiple different sources, and your user only has that one layer that they have to interact with. So finally, I just wanted to show you quickly
the code for how you execute the slash GraphQL endpoint, and the key piece is this. So we use schema.execute, and we give it our query and our variables, and that sends back the JSON data. So as a developer, you don't have to be super concerned
about all of the inner workings of how the GraphQL schema works with things. You just set it up and then execute. Okay, so finally, key thing to know about GraphQL servers. It knows about your schema, it has resolvers to get you the data that you need, and it's all running on this one endpoint, slash GraphQL.
Okay, so let's look at our client, which is how we can actually interact with this data. Now as I mentioned, I'm an Android developer, so I decided to make an Android app, but the point is, you can use it with anything. So if you wanted to make an iOS application, if you were doing this with web, it could all still interact with that same GraphQL server that we've created.
Now this app is written in Kotlin. It uses architecture components, and then Apollo Android, which is a great reference implementation of the GraphQL client. So to get our integration going, we're gonna need these three things, Apollo client, schema, and .GraphQL files.
So we'll look at them one by one. This is your Apollo client, and then these are the two key things, your server URL, as well as your OK HTTP client. Now does this code look familiar to anyone? It's very similar to maybe another library that we use a lot. Yeah, Retrofit, right?
So it modeled itself after Retrofit, which makes it really easy for you to bring it into your Android projects and play around with GraphQL. The next piece you need is the schema. Remember we said the schema is your contract between your server and your client, and you can use this command line, Apollo-cogen,
to download your schema. It stores it in a JSON file, and then you just plop it inside of your project. And I wanted to show you a little snippet of how it looks. So this is it. It uses a special query called introspection. We talked about that a little bit before, and it just grabs every single thing about your GraphQL schema,
puts it in this JSON file, and then now your client knows how to work with it, which is really cool. And then the final thing that you need is a .GraphQL file. It's nothing special about it. It's just a regular GraphQL query, but this is what the plugin takes advantage of. So when you create your .GraphQL file,
it goes into the plugin, and then the plugin is gonna generate a huge Java class for you, and inside of that Java class will be nested baby Java classes that do the heavy lifting of parsing your data, creating builders for you, and allowing you to interact with your GraphQL server
in a very simple way. So if we just take a quick peek, it looks something like this, where you'll have builders and variables and data. And then finally, inside the generated code, you can see even more pieces of information about how it's taking your schema and doing all this heavy lifting for you, basically.
So how do you now take these three things and convert them into our list of UFO sightings that we see here? Well, it's a three-step process. First, you have to build the query and queue the request, and then handle the response. Okay, so here we are, building a query. It's really simple.
There's a builder, you pass in any variables that we're interested in, and then we call build. Next, we use the Apollo client. We have the query method, and we give it our query. And then finally, we enqueue the response, so this is going to do the work for us on a background thread, and then we have to override these two methods on response and on failure in order to handle
everything that we get back from our GraphQL server. So the key thing here is that this is the data that you get back from your request, just like we saw before. It's the JSON object with the data and inside what you actually are interested in. But since you've used the plugin, all you have to do is call data sightings.
It's really, really nice that it hides all of that for us. And this is how we've been able to use GraphQL in order to add a new record as well as get a list of current records. And I'm gonna share the resources for it, but I really encourage you to play around with it so the code is open source for both the server and the client if you're curious in knowing more about GraphQL.
So my next thing would be to, just a quick tip, I say, is use the IntelliJ GraphQL plugin. It's really nice. I don't know if you kind of noticed this, like the purple, and I have this run button, things like that. You can install it inside of Android Studio when you're working with GraphQL, and it makes it so much easier
to interact with your server. A client is totally optional, so it's just regular HTTP requests. If you feel the need to bypass it for whatever reason, go for it. And then also, if you're on the fence a little bit, there are some public GraphQL APIs,
and you can just play with the work that someone else has created for you. Finally, there is a schema language cheat sheet that you can use as well whenever you're not sure how you want to structure the information. So I decided we should do some rapid-fire, true-false questions to make sure you understood everything that I just talked about for the past 20 minutes.
First, GraphQL was designed for graph databases. It's rapid-fire. Okay, false, right? No. You can use any database you want, or as we saw in the example, no database at all. It doesn't matter. It's just an abstraction layer for you to interact with your API. Next, GraphQL is language-agnostic.
True, yes. You can use any language you like. We already saw that there's a bunch of implementations available from C Sharp to Elixir, Kotlin, and more. Finally, REST is dead. Okay, right. Yeah, you decide. I personally don't feel that REST is dead,
but I really do enjoy working with GraphQL in my project and in my day-to-day work. It does allow us to iterate pretty quickly. So, yeah. Thanks for coming, and I hope you feel like you've been able to get a better grip on GraphQL.