GraphQL Basics - Build an app with the SpaceX API

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
graph QL a query language for AP is you define a schema for your data then tell graph QL how to fetch and supply that schema and in doing so amazing things might happen as we'll see in this video and 9 ignition sequence start in today's video you'll learn the fundamental concepts of graph QL by interacting with the public space X API if you're new here like and subscribe and I'd like to give a special thanks to Arjun ulam and Shelley who is the mastermind behind this video if you're looking for a graph QL expert you can find his LinkedIn and github in the description below let's start by answering the question of what is graph QL in the most basic sense it's a language that allows your front-end applications to communicate with your back-end applications a rosetta stone if you will a consistent way for your front-end to request data from your back-end despite any differences in the underlying programming language for example you're a mobile application might need to request a sandwich from your API it can make that request by sending a graph QL query the query will have the same shape that you expect to receive back from the API as JSON so in this case we expect a sandwich object with bread ham and cheese on the server graph QL also functions as a runtime for executing queries the server defines types for the data that's available there and also resolvers to actually fetch the data from a database or some other data source now because everything on the server is strongly typed we can get some really amazing tooling with graph QL to demonstrate this let's head over to the graph QL Explorer for the public space X API if you're the consumer or using the API in your front-end application you can do introspection to the backend to see what data is available there as you can see here we have a whole bunch of different checkboxes that represent different queries we can make to the space X API in the middle panel we already have an example graph ul query ready to go now go ahead and hit the play button to execute the query and then you'll see on the right side we get a JSON payload returned from the server and what you'll notice is that the properties on this JSON object are identical to the way we structured them in our graph QL query and on top of that everything is strongly typed if we hover over a field in our graph QL query you can see that it gives us a type there are several built-in types like string integer etc and the server can also define its own custom types so when working with QL as a front-end developer you'll always know the exact shape of the data that you're expecting back from the server and speaking of that let's take a second to look at the differences between REST API s and graph QL api's rest stands for representational state transfer and it's the status quo for API design that we've been following for the last 20 years now let's say our front-end application wants to make a sandwich and rest we might make three different requests one for bread ham and cheese each request is mapped to its own unique URL and each response from the server would contain the full JSON payload with everything that we need like the full loaf of bread a full Pig and a full wedge of cheese even though our front-end application doesn't necessarily need all that data we can just filter it out in the front-end code now in graph QL world things are quite a bit different instead of having multiple URL endpoints we just have a single entry point into the API so it's the actual query sent from the front end that determines what the back end will return it's not based on a URL or any specific mapping like that in addition the graph QL API will only return the actual fields that were requested instead of requesting ingredients one by one we just get the full sandwich all put together now let's say we also want to add a side salad and a drink to this query in graph QL it's a simple matter of updating the query but in rest we would likely have to make at least two more requests to two different unique URLs to get this data the beauty of graph QL is that it simplifies the way you request data from your front-end code so obviously graph QL is way better than rest and you should never use rest ever again right well it's really not that simple while graph QL provides a lot of advantages there are some disadvantages as well the biggest disadvantage in my opinion is that there is some added complexity up front you can build a restful service with Express j/s with like five lines of code but with graph QL you have some additional dependencies a type system and the benefits might not be that substantial if you're a small team or have a relatively simple API the benefits of graph QL really kick in when you have multiple developers working with a large API that needs to map together a whole bunch of different back-end data sources in any case graph QL is very fun to work with as a developer so let's go ahead and play around with some queries to space X let's go ahead and delete the default and then we'll make a query for all of the rockets in space X click the box for Rockets and then you hover over rockets you'll notice that it returns a query of an array of rockets a rocket is a custom type defined by the server and if we click on it we can see all the different data properties available there and then we can simply click the checkboxes for the properties that we want returned from this query and what you'll also notice is that queries can take arguments in this case we can set a limit to a specific number of rockets or we can offset it if we're doing pagination so now that we have a list of rockets let's go ahead and copy one of the IDS and make a request for an individual rocket go ahead and click the rocket box and you'll notice this query takes an ID as its argument and simply select the properties that you want to read on the rocket object and that's really all there is to it when it comes to fetching data from a graph QL API but there are a couple more advanced things that you should know about you can reuse values throughout your queries by using variables which you'll see prefixed with a dollar sign but sometimes you might actually want to change the query entirely based on the value of a variable for example you can see we have this glutton free variable so we might not want to include bread if that option is set to true so if the gluten-free boolean is true then it will include bread on this order but that's not exactly right so let's go ahead and do the exact opposite with the skip directive to exclude bread if it's set to true and it's also possible that your graph QL schema has a certain property that returns multiple types or a union type for example our sandwich might come with a side and that side might either be french fries or a salad if it's a salad if then we might want to return the dressing field and if it's french fries then we might want to return the side field so as a front-end developer graph QL gives you a lot of flexibility for structuring your queries and then it's up to your back-end developers to write the code to resolve the queries which tends to be the more difficult part in addition to reading data by making queries you might also want to write data or modify data on the server by using a mutation a mutation works just like a query but it's a convention that signals that some data will be modified on the server so now that you know the basics of graph QL I want to show you how to put it to use in an actual real-world front-end application the most popular way to work with graph QL from a front-end application is to use the Apollo client it's essentially a state management library that allows you to write graph QL queries then see the results automatically update in your UI Apollo has integrations for all the major JavaScript frameworks like angular react view etc including vanilla web components and also native platforms like iOS and Android what I want to show you over the next few minutes is a practical example combining Apollo graph QL and angular our goal is to create a simple web app that will fetch the recent launches from SpaceX and when we click on a specific launch it will take us to the details for that launch along with some pictures now as I mentioned earlier one of the big advantages of graph QL is the awesome tooling that it provides and when combined with typescript it gets even better you'll also learn how to convert your graph QL API into a series of interfaces that you can use directly in your front-end application so when you combine angular with graph QL you get end and type safety providing an amazing developer experience you can see here I'm in a brand new angular app and the first thing I want to do is install the Apollo graph QL extension for vs code it provides syntax highlighting and everything else you need to work with graph QL and vs code from there we'll go to the root of the project and create a new file called Apollo config KS this will tell Apollo where to find our back-end API which in this case should point to the public space X API the next step is to generate a couple of components that we can use for the screens in this app we have a ListView that will show all the recent launches from SpaceX and then also a detailed view we can generate these components with the angular CLI and we'll also set the change detection to on push which is just a little performance optimization that we can use here because with Apollo and graph QL the only thing that we actually need to do is subscribe to observables for our data so we don't need to use angular's built-in change detection the next thing we'll do is jump into the app routing module and set up routes for these actual components we'll set the route route to our launch list component that's the default route that user lands on then if they click on one of the launch cards it will take them to a URL parameter with that ID and show additional details about that specific launch that takes care of our routing configuration now let's go into the app component and delete all of the boilerplate code that comes with a default angular app just make sure to leave the router outlet and now we're ready to write our first graph QL query and the reason I want to do this first is because as you'll see in a minute here we can use the query to automatically generate angular services interfaces and basically everything else we need to work with our back-end data go into the launch list component and create a new file called launch list graph QL now unlike the interactive editor we'll start out our query by writing the query keyword and then we can give that a name called past launches list and we'll have it take a parameter called limit which will take an integer argument and the exclamation mark after the type makes it required then inside the query we'll write some graph QL code just like we did earlier in the video we'll make a reference to the launches past query that's provided by SpaceX and then we'll pass in our limit argument from there we'll add the actual fields that we want for each individual launch object like the idea mission name links to some images and so on so this defines all the data that we want to show in our launch list component and now we'll move over to our launch details component and do the same thing by creating a launch details graph QL file one thing you'll notice on this query is that we have a required type of ID the ID type works just like a string except that it signals that it's a unique value and we can pass that ID to the launch query in graph QL and then filter by the fields that we actually want from the API so now that we have our graph QL queries in place we can generate a whole bunch of code automatically the first thing we'll need to do is integrate Apollo into this project so head over to the command line and run ng add Apollo angular this command will install our Apollo dependencies and also create a graph QL module in the app directory go ahead and open up that file and tell it where to find the graph QL API by modifying this URI variable so that takes care of the setup for Apollo but we want to generate a lot of our code automatically as opposed to writing it manually the tool that can help us do that is the graph QL code generator this is a really awesome tool that you can use on both the backend and front-end to look at your graph QL schema and then automatically generate typescript interfaces and in our case angular services that can fetch the data from the backend we have this big long install command and you can copy and paste that from the lesson repo once those are installed we'll create a code gen Yama file in the root of the project this simply tells the code generator where to find our graph QL files and what to generate once it finds them and now that we have that configuration in place we just need a commander that will actually run the generator we can do that by going into the package.json and going into these scripts will create a new command called cogent that runs the generator then we can open up the terminal and run that command and you'll see it generates a new directory called services with a service that we can use to fetch data from the graph QL API now the cool thing about the code generator is that it looked at the actual schema of the SpaceX API and also our local graph QL queries and combine the two together so we now have an angular service that has all the interfaces from the SpaceX API and also methods to fetch the data that we actually want based on our own local graph QL queries that was quite a bit of configuration to get started but now that we have that done we really only have to focus on writing components and writing graph QL queries now let's go ahead and finish things up by writing the components for the user interface to make things look nice I'll go ahead and add angular material to this project by running ng ad at angular material and then in the app component I'll import the material card module from there I'm going to head over to the launch list component type script and the first thing I'll do is inject the past launches service in the constructor remember this service was automatically generated by the code generator the service is able to fetch the past launches from SpaceX by using the fetch method and then we can pass in a limit argument and set it to 30 the response is going to have some additional data that we don't really need so what we'll do is pipe in the map operator and then we'll just map the response down to the actual data that we want to show in the UI which in this case will be the response data launches past now if we go into the template we can unwrap the past launches observable by using the async pipe and then we'll set the result as a template variable called past launches the past launches will be an array of launch objects so we can simply loop over them using the ng for directive and angular that will give us a material card for each individual launch and then we can add a router link that will point to that specific launch ID so when the user clicks on a card it will route them to the launch details component and then everything after that is pretty standard angular templating will display a material cart header with an image and then a title and a subtitle at this point you should be able to run ng serve from the terminal and then open up local 4,200 and see a list of launches from the SpaceX API now at this point when you click on an actual item it will take you to the launch details component but we haven't actually built that one out yet so let's go ahead and do that now go ahead and open up the launch details component type script and then we'll import activated route from angular router and also our launch details graph QL service and then we'll go ahead and inject those and the constructor the reason we need activated route is because our graph QL query takes an ID as its argument and we get that ID from the URL in the browser angular provides all of the URL parameters as an observable which we can access on the activated route per a map when we have that observable we want to switch to an observable of the actual data from graph QL that's a perfect use case for the rxjs switch map operator in other words once we have the ID parameter from the URL we'll go ahead and switch to another observable which in this case is the launch detail service fetch of that specific ID and then like we did in the previous example we'll go ahead and map the response down just to the raw data because we don't need any of the additional metadata that comes back with the response and then also like we did in the previous example we'll unwrap the observable at the top of the file by using the async pipe and then we'll set a template variable as launch details and from there we simply add some HTML for the UI and interpolate the values that we want to show to the user and keep in mind I am using a few custom CSS Styles here you can find those in the full lesson repo and if we go back to our app you'll notice that when we click on a launch it will show the actual launch details and some additional photos in the detail page congratulations you now have a full stack Apollo graph QL powered angular app now if you want some extra credit I'd recommend going to the full lesson repo give it a star and check out the extra credit section at the very end it'll show you how to build an angular pipe that will format the actual dates of the launches in relative time for example it will say a launch occurred 10 seconds ago yesterday 5 days ago and so on I'm gonna go ahead and wrap things up there if this video helped you please like and subscribe and consider becoming a pro member at fire ship IO to get access to even more thanks for watching and I will talk to you soon five four three two one zero all engine running [Music]
Info
Channel: Fireship
Views: 201,419
Rating: undefined out of 5
Keywords: webdev, app development, tutorial, graphql, graphql basics, graphql tutorial, graphql angular, graphql javascript, js, javascript, schema, spacex, spacex graphql, apollo angular, apollo graphql, apollo client, code, learn to code
Id: 7wzR4Ig5pTI
Channel Id: undefined
Length: 15min 47sec (947 seconds)
Published: Wed Oct 09 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.