Basics of GraphQL in Ruby on Rails - Reading Data | Alex Deva | Skillshare

Playback Speed

  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x

Basics of GraphQL in Ruby on Rails - Reading Data

teacher avatar Alex Deva

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Lessons in This Class

12 Lessons (33m)
    • 1. What we'll do

    • 2. JSON

    • 3. Introduction to queries

    • 4. Query arguments

    • 5. Query context

    • 6. ActiveRecord queries

    • 7. Scalar field types

    • 8. Compulsory field types

    • 9. User defined (ActiveRecord) fields

    • 10. Custom field types

    • 11. Arrays

    • 12. Assignment 1

  • --
  • Beginner level
  • Intermediate level
  • Advanced level
  • All levels
  • Beg/Int level
  • Int/Adv level

Community Generated

The level is determined by a majority opinion of students who have reviewed this class. The teacher's recommendation is shown until at least 5 student responses are collected.





About This Class

This course teaches the basics of using GraphQL in a Rails application. GraphQL is a query language invented by Facebook in 2012, and made open source in 2015. While it has certain clear advantages over REST, it also has a somewhat steeper learning curve.

Structured in a simple and accessible manner, these lectures will help you get on your way to using GraphQL to circulate data between back-end and front-end applications.

After an introductory class, in the next class we will learn about reading data; in the third, about changing data; and the slightly more advanced fourth class is about protecting data.

This is the second class: Reading data.

Meet Your Teacher

Teacher Profile Image

Alex Deva


Class Ratings

Expectations Met?
  • Exceeded!
  • Yes
  • Somewhat
  • Not really
Reviews Archive

In October 2018, we updated our review system to improve the way we collect feedback. Below are the reviews written before that update.

Why Join Skillshare?

Take award-winning Skillshare Original Classes

Each class has short lessons, hands-on projects

Your membership supports Skillshare teachers

Learn From Anywhere

Take classes on the go with the Skillshare app. Stream or download to watch on the plane, the subway, or wherever you learn best.


1. What we'll do: welcome to the second section of the scores, in which we learn how to pass state or from the back and application into the front and application. Now the front and application can be anything. It can be a desktop application. It can be mobile application or can be a Web based applications. Something may be written in angular or re actress. We're not going to constrain the course to the specifics of one front and framework. Instead, we're just going to use graphic you'll to navigate the data that we're exposing from the from the back end. The important thing to know is that in graph D well, we read data. We request data using something called Queries. And when it comes to changing data on the back end, when it comes to making changes in database, perhaps we're going to use something called Mutations on. We're going to talk about that in another section. It's also important to know that in this course, we're going to use graph kill to pull data from the back and into the front end. There are some advanced graphical features which allow pushing date, unlike subscriptions and the life quarries, but we won't be talking about these now on. The other thing is that all data, which is circulated between the back and on the front end, is encapsulated using the Jason format on. We're going to be talking a little more about Jason in the next lecture. 2. JSON: Jason is a relatively new standard. It emerged in the late two thousands, and it only became an international standard in 2013th. The Wikipedia article for Jason says that it's an open standard, former that he uses human readable text to transmit data objects consisting off attribute value pairs on array data types or any other C realizable value. What this means is that Jason gained a lot of traction because it's easy to use on. This is the standard that Facebook also adopted when they invented graphical. Jason looks like text, which is enclosed by curly brackets on, As the definition states, it has keys and values or attributes and values, and the attributes are always strings enclosed in double quotes. And the values can have one of several. The tapes, types and the basic data Tapes and Jason are numbers and strings billions as well as raise objects and the special No value. This is an example of Jason text on DA. As you can see here, we have a number of value. He will have a bullion value. This is an array which in terms contains objects, and this is a 90 ray and this is a no value. Jason is very important graph girl because this is the standard which encapsulates all the data which is passed to and from back in from 10. And we're going to see an example of such data in the next lecture. 3. Introduction to queries: So let's return to our application For a moment. We've tried the default query test field Onda. We've noticed that it works its return Hello world, and we've noticed that it's listed in the documentation, which is very helpful if we look back in the code where this, um, field the test field is defined will find it in the query type file, which leaves right here in the types father of graphic you'll on. Let's look a little bit of it. It's defined as a field. Fields are what make queries and in particular root level fields or fields that don't belong to any other object. They just are. We can just refer to them, for instance, in ah graphical as we did here, without having a sort of a parent. For them, they just aren't just belonged to the root of ah, query. So let's look at it a little closer. It has a name here, which is listed with which is given with an underscore and lowered his F where, as in graphic you'll we referred to it with in camera case with a capital F and no underscore. I'll talk about that soon. It has a type, which is string. It has the characteristic of not being knowledgeable again. We'll talk about that in a few lectures. This field cannot have a value of nil, and finally, it has a description which, which appeared in the documentation. So whatever we type here, I will helpfully be reflected in the recommendation. If if we reload graphic you'il there you go on finally next to the field. There's a little method, and the method has exactly the same name as the field. And whatever the method returns is the result of the query on the field. In this case, the method returns a string, which is what we expect. This is not a null string. It's a non story. It's a string. Continue the text. Hello world, and this is what ends up in the front end. So this is the basic architecture of a field on. We're going to define fields to retrieve and to change date on the back end during the whole duration of the scores 4. Query arguments: in this lecture, we're going to talk about query arguments. No field fields in ah graphical may have arguments, which is something that might be passed along from the front end. It might influence the response that the field office the way to define an argument for a field in graph in a graph deal. Jim is to specify a block a ruby block after the field definition. So inside the ruby block, we say argument, Andi Ah, we'll give it the name Name will say that it has to be a string and will say that it is required. Always having done this, we can now expect to have this argument in the test field method on the way to do that. Easiest way to do that is to use a ruby named Method parameter, which ends in a in a column. Now, having access to these variable all the way up in the method, we can just replace the world world and, ah, put name instead so that we can greet where we want. So how do we specify a query argument on the front end if we switch quickly back to year to the test field on By the way, let's reload just to see the documentation again for the text field. The test field no has an argument, which has the name, name, and it is the type of strength, and it already suggest to us how it's done and graphic your will very helpfully provide the name of the arguments here. We can just use a normal Jason notation to say, Oh, gruff, que will on if we're on the square, we'll see that the argument made it all the way back into the back and and was interlaced into the into the response string, and it came back up in the front end. 5. Query context: Now, before we move on and we talk about databases, I want to do something else, and I want to show you that in this method here in this matter, which defines what a field will return we have access to, among others, in a variable, an object called context, and we're just going to lock that just to see what's in it. I'm going to open up the log here on If we make a request again, we'll see that it's a complex object of the of the class query context. And if we pop over to the rock, your documentation, we can find it here. It's an object that exposes some quite a specific information to field result of functions it delegates and anti ray to the hash that's passed, too. Graphic your initialize on. This sounds a bit complicated, but it's really not. Ah, context is an object which is passed to all the queries. All the fields and its origin is in the controller. That graphic your generated for us? It's called graphical controller on this time, as again, easily see, it's just in empty hash. We can just put whatever here say time is time to know on DA we can access that information inside the context. Object, for instance. For instance, if you save time, we're going to look for time and we can see that that it's been logged here and this is going to be very useful later when we talk about authentication and authorization and all that use the management stuff, because this is where we're going to be keeping the current user. But for now, it's just important room. Remember that this object exists and it's possible to pass context information contextual information from the graphical controller, which is where all the HDP requests come in all the way into each and every field. 6. ActiveRecord queries: it's time now to do something useful with their application and connected to a database. By default. These rails application uses a sequel I database, so that's fine. Weekend. Jump right ahead and use use rails, migrations to create a model. We're going to generate a model, and we're going to call it author. And ah, another is going to have a first name, last name on a year of birth on. We're going to also add bullion, which will tell us if the author is still alive or not. Ruby Mind will tell rails to create him. Migration for us. This is the migration on. I'm just going to run it quickly and it's done. Now we have the author table in our secret. It obvious. Good. So how can we retrieve on DA change authors in the database? Well, first of all, let's create a north or so we have some data to play with, and I'm going to start a rails council now. Just quickly create an author, Andi, just for the sake of the exercise, I'm going to create another one. So having created some data in our database, we have to think about how we send this into the front end using graphical. Well, we can't send it as strings. We can't send it as an array on anything else. We have to send it as its own type because an author has its own fields. So for that we have to create something called an author type, which will describe on author, and that's going to be its own file here in types. We're going to create a new file, and I'm going to call it author type There will be filed and it will look like this is going to be a ruby class in the name space of types because of the types directory where this file is and I'm going to call it or for type as promised by the file name, and this is going to inherit from the base subject type. We're going to give a description to this type. This will surface, and we're going to say that it has ah, on all those fields that the we just created using the rails migration first of foremost the I D, which is of the graphical type I D. And we'll talk about types in the next life lecture and this can never be no. Then we have a first name, which is a strength, which can be no last name. Similarly, Year of Birth, which was an integer that is a life which is a 1,000,000,000 might as well be true. Having defined this type and save it, I can now create a query. Onda quarters are defined by fields, so I'm going to create a route field for another. This is the root level field because the North doesn't really depend on anybody. It's Justin object in its own right. So I'm going to create a field which I got to go author. And whenever equities made for a North earthy answer is going to have that author type, which we just defined on a new author may perhaps be no, and we can also give it a description now, in order to know which author are the front. And once they're probably going to want to pass us the I d of the record. So this field will have on argument, which is going to be the date of his I d. Always required right. We've defined the field. Now let's define a method that will actually feel in something for this field deaf author. Would you find an author that will have this I, d. As a method, parameters and method name parameter and will simply look it up in a database? The if we now switch over to graphical and reload. I do that with command are on my mark. And we look at the scheme again, will notice that a new field has appeared author with the description that we've given it and it will have the type author which has first name I d is alive. Last name and year of birth. We can quickly test that I can, um, retrieve a north away the idea of one. And for that author, um, request Ah, first name and last name. And I get Isa Qassim of so one thing it's important to know this year is that there's a bit of a change between the way I've spelled first name, last name and his life and the way they appear in the schema. As you've seen the code, I've spelled them with the well in the in the migration. Actually, I've spelled them with the underscores, but in the scheme, aren't they appeared camel cased on. That was the same case with test field. The reason for that is that camera case is Thea recommended notation for JavaScript and Jason. But if we don't want to be inconsistent, we can change this fact in the in the type of the final the fields. And if we've spelled them with another score and we want them to be to be left alone, we could just say caramelize falls for this field and for this field and then for this field. And if we do this and looking the, uh, documentation Explorer again, the author type will now have the name is exactly as we asked for them. If we're going to run the square again, we're going to get in better, because now the field has a different name. So we have to rename them in the query. And this time I'm going to ask for a year of birth and quit. It works again 7. Scalar field types: So let's recap here. We've had the test field, which was the default query left for us by the graft your developers and we've created another field called Author with its own resolve method. This is the method which resource the field into some data for the front end. And we've also created the type for another which defines intern all over the authors fields. And now you can see the difference between a field that is not a route field and all these root fields here. Inquiry type. Ah, these fields and author type are not route feels because they belong to another. Let's look a little bit at the types that these fields have. As you can see, I've used types called I D String integer on bullion. There are, as it turns out, five scaler types that graphic UAL offers, And if we quickly looking the documentation, we'll see them here. 12345 on Integrys assigned 32 bit integer and so on. Um, the only one that's, um, rather more interesting is the idea type, which represents a unique identity. Fire on this is usually used when it comes to database. I DS and it's always serialized as a string, but it doesn't really matter what's in it. It's just Ah, the the only intention with it is that it's not supposed to be human readable. Ah, in my sequel or sequel Light, Which raising now ideas are consecutive numbers, consecutive integer numbers, starting with one. Ah, whereas if using a date of is like Mongol, for example, the ideas they're going to be strings eso That's why graphical it represents them all as strings. If we pop over to graphic, you will and requests the i d of another, we're going to see that. Ah, it's returned as a string. So we have five scaler types that we can use out of the box with any field definition graph you well and ah, they are ah integer float string bullion on I d 8. Compulsory field types: Another thing that you may have noticed was all this talk about knowledgeable fields fields which may or may not have a value of nil. Every time we define a field in the new version of refuel, we have to say whether it can, um, turn out as Neil in the front end. And you see here that the test field may not ba No, Um whereas another may. In fact, we know and we feel looking the old type we've defined the first and the last name as knowable. If we change this and, uh, make make it so the last name cannot in fact be Neil and then create another author that doesn't have the last name in the console really quickly. Just create another with, ah no value in Ah, it's ah in any of its attributes. And we try to retrieve this author, which I'm guessing we'll have an idea. Three and ah get its last name. We're going to get annettor, uh, with a message saying that it cannot return no for the non knowledgeable field. Last name of author. This is going to work again. Obviously, if we switch back to true, then the last name is just going to be No. All the fields have to have a defined nal ability, value either of true or false on DA This, in addition to the type on the name are the only three features of a field that are entirely compulsory. 9. User defined (ActiveRecord) fields: let's continue now and create a custom field, a user defined field for our active record object. The author. We can do this in two ways. What we want to do is return the full name of a norther into the front end. So concatenation of the first and the last name and there are two ways to do this is I've said one of them is to do it in the, uh in the model in the active record modeling the author model, we can easily define the method here called Full Name the way it's done here. Um, using the compact method here has the advantage that if either the first name of the last name is missing, we won't have a next space. And now all we have to do is define this field here in the Ortho type, will know that it will be a string because it's a concatenation of strings and, well, let it be Neil for now, on going to also disable camel ization, right popping over to the graphical query. If you look in the schema for a north or not, we have a full name, which is a type of strength If you go back to Mr Isaac Asimov and ask for his full name, we're obviously going to get the string as a consumer. Now, the second method to do this is rather than do it in the model, I'm just going to move. This logic right here in the field on this field is going to become a little more complex because we're going to have this method here that defines it with this is called the resolver method. The method that results this feeling to something. And we can't just talk about first name and last name here because we're not in the context of of a model where self is the actual model we have Teoh use something else here and other than the context object about which we've talked, you know, if your lessons ago and which will pick up again soon, we have access to something called object. So this is the object that's the parent of all these fields. The parent of all these fields, in our case is an author. So the kind of instant a specific kind of instance which was returned for the author field , which is an active record instance here is going to be subjected to a cussed a type cost. Ah, on DA All these fields are going to retrieved from it. And in the case of full name, which is no longer well, it has never been a database field, and it's no longer a model model method. Either. This is going to be resolved by a method defined in the actual type, and this method makes use of the object reference. And again, these will point out to the author, which we find in the data base beforehand. So if you save these and try it again, we'll see that it works equally well. It's the same thing. So once again, the logic here is that in the query we ask for a new author on the query is here This is a root field. It is resolved by retrieving an instance of an author from the database, and then it's type, which is matched here. Ortho type is cost on that result. The active record object on a a number of fields in this case what six fields are obtained from it. The 1st 5 are taken straight from the database, and the fifth is sort of sixth is resolved using this method by means of the object reference which points to the parent. This will hopefully appear not clear with a little bit of practice in the next ah, election, we're going to talk about custom field types and I'll see you there. 10. Custom field types: in this lecture, we're going to define a new type in your field type. This is going to be a custom field type on the use case I thought about for that was well to add coordinates for another two at latitude and longitude to give us the position of another. Not the most realistic of use cases, I admit. But it will have to serve for that. We're going to add a model, a method in the model which will just return some random numbers for latitude and longitude . We'll call it coordinates, and this is just going to return on the ray of random coordinates. Now, if we at this in Ortho type and we present it as an array to the front end, we might have the problem of not being able to distinguish between which one is the latitude and which one is the longitude. Admittedly, we could use a hash here and name all of them, but I want to show you how to make a costume fuel type. So we're just going to leave the right here and we make we're going to make a custom type, which is going to define a pair of coordinates. And for that, we're going to create a new file here in types and we go to call it co ordinates type. And this is going to be its own class as all the other types it really heard from the based object and it's going to have to fields and we're going to resolve each field. The latitude is going to be by convention. The first element of on the raid on longitude is going to be a lost one. Now, this is going to be again by convention. I decide that the first element of this array of of this pair is the latitude and the second element is the longitude. Uh, so graphic your doesn't really like convention. Everything has to be described and clear so that if a lot of people are working on the same project, things should be obvious to everybody. So to do that, we've created this custom type and it describes will a pair of coordinates and it's ah, simple class of the same name, name, space of types. And now all we have to do is tow remain cities for us to actually use it. And we're going to have it as an extra type for an author. We're going to call it, uh, coordinates. It's obviously going to have the type that we just defined. No resolve. Method is required for this thing. And that's because the name of the field matches a method on the model. Remember what we did in the previous election with the first night with a full name, we had a method on the model, and we have the same concept here. We have a method on the model, and if the name of the field corresponds to a method on the model, then all graphical is going to do is will be to Cust, the type that we tell it according this type upon that object. That object in our case is an array of two elements, um, or a pair, and it's going to be visible inside the type definition using the object reference. And if you take the 1st 1 and call it a latitude and the last one and call it longitude, then we have these two fields. So if we pop over to graphic UAL and see how this works, we get a list of coordinates and because they randomly generated every time a north or is retrieved the fight round the quit again. We're going to get different numbers. If we reload this and look in the ah schema documentation will notice that a new field has appeared for another coordinates, which has the type coordinates. The exclamation mark at the end means that this field may not be no. So it's not knowable hit. It cannot be Neil in Ruby or no in JavaScript. And if we look at the type, we have to fuse that we've defined of the type float and this is how we make our own type our own custom type in graphic you'll to represent nonstandard data in a way that is both. 11. Arrays: in this lecture, we're going to talk about a raise, how to return. Using graphic. You will on array of values into the front end, and we'll do that in two parts. First, we'll talk about a race of Scalia types like basic ones integrate, float bulletin, salon. And then we'll talk about the rays of custom types. Now, if you wanted to make a showcase of an array in the context of a North ER, one of the things that comes to mind is a list of publication. Yes, the years when another has been published again. This is a lot easier for me to fake than to research. So I'm just going to make a quick method here called Publication Years, which is going to return on the rate of random values. As you see, the array itself has a random length. Now. How are we going to return these years as part of the data for another? Well, we're going to create another field for that. We're going to call it publication years on because the field has the same name as the method in the model, it will be recognized. Ah, the type of this field is going to be on the ray of integer values. And we say that using square brackets like this this means an array of values which are of which are each integrates. And ah, this will not be knowable. Now if we switch over to graphic, you will. And first of all, looking the new documentation for the Ortho type. We have publication years on array of non mobile, noncallable integer values, which itself is not unknowable. And we asked for a list of publication years. This is comic. It's because I didn't ah specify it complicates false. We're gonna get the ray of, ah, fake years. If we try it again, we're going to get a different tree. If you wanted a list of more complex data, for example, the least of all the authors where on author has a more complex time, it's not scaler. Then we would do that a little differently. We might then add a custom route field in the query type file. Might as well call it authors, and this is going to have again array type on right that using square brackets like this, it will not be knowable. Onda, uh, we're going to add a resolver method for it, which will seem to return all the authors in the database. If we try this in graphic, you will and asked for i d of full names of or the authors were going to get a list of our three authors. The last one, if you remember, had no attributes a tool. So this is how we handle a race. In graphic. You will, both with scaler values and with more complex types. 12. Assignment 1: it's time for it'll homework. Why don't you try and put your skills to use by creating a simple back and for a block application, start by creating on rails AP I app empty one and then create models for a user which should have a first name or last name of street number city postcode in country. And then a post, which is to say, block post that we have a user i d and the body and the user will have many posts, and the Post will belong to user. And then thirdly, a comment which will have a post i d and the body and obviously a comment will belong to opposed and a Post will have many comments and then create graft your queries to retrieve an individual record of each of these three models and then at fields in the use, a type to include all of Gaza's posts and then imposed to include all of that. All of the comments for that particular post and then, lastly, the user types would have a custom field, which should return the full address as one single string. I'll add my own solution to the course and good luck