# Should you use GraphQL? (Everything you need to know about GraphQL)

## Метаданные

- **Канал:** ProgressiveCoder
- **YouTube:** https://www.youtube.com/watch?v=PWgnZir7zyg
- **Источник:** https://ekstraktznaniy.ru/video/39038

## Транскрипт

### Segment 1 (00:00 - 05:00) []

as the complexity of software applications grows there is also a rise in number of interfaces between different systems this leads to an ever growing api footprint an explosion of integrations between clients and servers ultimately this results in a maintenance nightmare even minor changes start taking more and more time to implement you need to analyze more test more and even then there are chances that issues might creep into your application more often than not refactoring appears to be the only solution to handle the ever growing maintenance costs however refactoring is a costly business and usually it does not get management approval unless there is a very strong reason to do so what is the solution to this tricky problem this is where graphql steps in graphql is a tool that brings paradigm shift in the way clients and servers communicate with each other while it is on a silver bullet by any means it can definitely act as a sweet spot between a complete overhaul of the application or doing nothing at all have you still not subscribed to the channel then what are you waiting for you don't want to be missing out on any future videos of cs trekker subscribe now and don't forget to press the bell icon as per wikipedia graphql is an open source data query and manipulation language for apis it is also a runtime for fulfilling queries with existing data in a sense graphql stands for graph query language but don't let those words mislead you graphql is not like sql while it may be dubbed as a query language we don't query typical database tables using graphql is more of a format or structure to define the contract between the client and the api server basically you can think of graphql as a specification or a new api standard similar to rest however it is often considered more efficient and flexible when compared to rest in fact we can practically use graphql wherever we were using rest in a way graphql aims to do what rest was doing only in a much better way so how did graphql really start graphql was initially developed as an internal project at facebook sometime in the year 2012. according to the co-creator of graphql lee byron the concept of graphql emerged when they were trying to design a native ios news feed using restful apis they immediately encountered a bunch of issues the api requests were slow on the network coordination of requests for different models was problematic multiple round-trip requests had to be made on flaky mobile connections api changes had to be carefully carried over to the client code to prevent the app from crashing api docs were often out of date from the actual implementation it is said that necessity is the mother of all inventions and feedback is the father of all improvements the goal of overcoming the challenges caused by using normal restful apis led to the birth of graphql was publicly released in 2015 and ultimately in 2018 the graphql project was moved from facebook to the newly established graphql foundation currently the graphql foundation is hosted by the non-profit linux foundation at this point you might be wondering how graphql works and what makes it so special think of a vending machine get an item from the vending machine we press a button and we get one to get the second item we press another button if we have to get 10 items we press 10 different buttons this is how the restful api approach works for every piece of data the client needs to make a new request needless to say the process is slow to get around this inconvenience the traditional approach has been to create special end points think of it as a vending machine having special buttons to get a combination of items every special button handles a particular combination of items the problem however does not go away how many special buttons would you create there might be hundreds of combinations a user might be interested in even if you create a hundred still buttons you can never be sure that the customer might not look for a new combination clearly this approach is not suitable there is a third approach as well what if the vending machine support an option to choose multiple items by pressing a combination of buttons basically the user tells the machine exactly what it needs and once that is done you get everything in one go this is the essence of how graphql works a graphql api depends on what the client actually needs the client specifies exactly what it needs and the graphql server provides everything in one go this is unlike restful apis where the server controls everything and the

### Segment 2 (05:00 - 10:00) [5:00]

client has to often make multiple requests now that we have a basic overview of graphql it is time to look at some important features of graphql point number one graphql is declarative in graphql clients ask queries to the server these queries are declarative in nature a typical graphql query may look like this it is pretty self-explanatory basically the client is asking for the book with id of one also the client is specifying that it is only interested in the fields title and publish year the graphql server has to make sure that only the fields specified within the query are returned as part of the response as you might notice this is a totally different approach from rest api design in rest api design the client has very little control over what gets returned from the server second point graphql queries are hierarchical in nature in this example the client is asking for the book with id of one however along with the book the client is also interested in getting the author related information of the book especially the name of the author in graphql queries can describe this type of hierarchical relationship quite easily the third feature is type safety in graphql we have to declare schemas to specify our data models a graphql schema helps the server determine whether the client's query is valid or not these schemas are strongly typed a basic schema looks like this each attribute in the book type has a data type of its own the type system can use primitive types such as numeric integers booleans and strings however it is also possible to use complex types such as objects apart from the features there are certain core concepts of graphql these core concepts form the backbone of graphql and it is important to know about them number one we have the schema definition language or sdl as we saw earlier graphql has a type system it is used to define the schema basically the syntax for writing the schema is also known as the schema definition language or sdl a very simple schema may look like this schema describes an author it contains only one field the name of the author the exclamation mark here denotes that name is a mandatory field concept number two we have queries are arguably the most important concept of graphql clients make queries to the graphql server these queries specify the requirements of the client if the query is found to be valid the server sends a response this is an example of a typical graphql query where we specify the id of the book and the specific fields we want to fetch the third concept is known as mutations as we all know apis are used not only to query information but also to update information in graphql updates are supported using the concept of mutations a mutation looks like this as you can see the mutation syntax looks quite similar to the query syntax however the mutation keyword makes the graphql server aware that the client wants to perform an update or create operation the fourth concept is subscriptions in many modern applications it is important to have a real-time connection between server and client so that the client can be immediately informed about important events subscriptions don't follow the typical request response cycle when a client subscribes to an event it will hold the connection to the server when a particular event occurs the server pushes the data to the client in graphql subscriptions are also written using the same format as queries and mutations once the client sends such a subscription request to a server a connection is opened between them whenever a new mutation happens that results in the creation of a new author the server sends the requested information to the client now that we have a pretty good idea about the features and concepts of graphql it is time to see graphql in action and to do so let us start with creating a very simple graphql api server basically there are three things a graphql server needs to work properly a web server graphql schema with a resolver a request handler to process incoming requests first for the web server part we will use express a popular node. js framework for building apis second the schema and resolver are handled by the graphql package this is a standard graphql implementation for javascript and forms the basis for other sophisticated implementations lastly for the request handler part we will use the express graphql package this package is basically a middleware for express that helps us handle incoming requests in the first step we will create a project directory and install the required packages for any of this to work you need to have node. js installed on your system next we create a file named server. js inside our project and place this code in that file

### Segment 3 (10:00 - 15:00) [10:00]

let us walk through what's going on in this particular code after the necessary import statements we define the schema using the build schema function then we specify the root query and register one query type named hello next we set up the express app and implement a request handler to handle incoming requests within the request handler we configure the graphql http middleware to use our schema and the root query a typical graphql server usually has only one endpoint all queries are processed by the same endpoint unlike rest apis where each resource has its own endpoint here the single endpoint is graphql the graph iql flag is set to the value true this flag enables the graphql user interface for our application where we can play around with the queries and see the responses from the server we can access the ui on http localhost 4000 slash graphql having seen a working demo of graphql we are now in a position to compare graphql with rest apis there is no denying the fact that red has been an industry standard for the past several years however rest apis are often inflexible and don't adapt well to the changing requirements of the client this is where graphql offers benefits when compared to rest apis the first major problem with rest is that you end up over fetching data this is because in the rest approach each endpoint has a specific layout even if the client needs only one field from that layout the api will return all the fields whether you like it or not this results in over fetching of data while overfetching is a problem there is another bigger problem with rest and that is under fetching data it is quite common that a single api endpoint in a restful approach does not provide the complete information that is needed by the client we make an api call get some response and use that response to make another api call to get the rest of the information depending on the design there can be multiple calls to accumulate required data this is also known as the n plus one problem this illustration demonstrates the n plus 1 problem where we have to make multiple calls to fetch the book and the author details when following the rest approach in graphql this problem does not occur this is because the clients can write hierarchical queries with nesting information going further rest apis can lead to unnecessary network traffic due to multiple api calls in other words more data goes over the wire in the case of graphql the same amount of data can go through a single call using proper hierarchical queries lastly with rest apis it is hardly possible for the server to determine what the client is doing with the data and what fields it is actually interested in the server simply sends everything and forgets about it in graphql clients send specific queries imagine the use of this information from an analytical point of view monitoring of graphql queries can result in future improvement to the api offerings depending on what kind of queries are being asked by the client as we have seen till this point graphql is extremely flexible due to this reason it provides a lot of flexibility when it comes to the architecture of your application on a high level graphql follows the typical client server architectural pattern the client makes a request and the server provides a response however there can be several variations in terms of how to structure a graphql server first we have the graphql server with a connected database this architectural pattern is most suitable if you are starting a brand new project basically something like a green field project in this setup we have a single web server this server implements the graphql specification as per the core concepts of graphql when a query is received the server resolves or processes the query and returns a response though we have marked the transport protocol as http it can use any other protocol as well this is because graphql is transport layer agnostic also graphql server can connect to any database solution such as mysql mongodb or aws aurora the advantage of this approach is low complexity in terms of data fetching the data source is also close to the application logic due to which there is less latency if possible this is an ideal pattern to use however it is possible only in the case of a new project where everything is done from scratch in an existing application where we want to utilize existing parts of the system we need to examine some of the other patterns second we have the graphql layer with existing systems graphql provides a lot of flexibility to the client in terms of building a query and requesting for information however an existing system might already be built using different solutions such as third party apis legacy services and a bunch of newer microservices considering

### Segment 4 (15:00 - 18:00) [15:00]

this one might assume that we cannot use graphql in such a scenario but this is an incorrect assumption as you can see graphql can unify the existing systems and hide their complexity behind a unifying graphql api new client applications can simply interact with the graphql api without worrying about the underlying systems the graphql server will be responsible to resolve the queries and package the responses as per the client's requirements this approach can suit a lot of big organizations where a large number of existing services are already present and it is time consuming and risky to duplicate the business logic for new requirements the third pattern is basically a hybrid approach it is a combination of having a connected database as well as talking to existing legacy systems in this approach when the graphql server receives a query it will resolve it by retrieving the data from the database or talking to one of the services this approach can also pave the way for slow migration of business logic from legacy systems to the new graphql servers one could incrementally put more and more functionality into the graphql server and connected database while slowly deprecating old services finally it all boils down to the advantages and disadvantages of graphql this particular section is important because these are exactly the points that may help you decide whether you want to use graphql or not from an advantage point of view we can say that the api clients get way more freedom with graphql the client applications can formulate queries depending on the requirements without being extremely dependent on the server since graphql uses schema definition language based on type safety it provides an automatic layer of validation developers consuming the graphql apis can easily see what the schema supports and accordingly formulate the queries from a disadvantage point of view since graphql supports hierarchical queries complex queries with a lot of nesting can often lead to performance issues to avoid these issues we might have to implement rate limiting or nesting limits to our graphql queries while graphql is a great tool to reduce complexity it might even be an overkill for small applications for a simple application a rest api might be a better option resql does not support http web caching at the end it is important to note that graphql is a wonderful tool to build apis that are adaptable to evolving customer needs if your application's api footprint is growing out of hand and you have got a bunch of disgruntled consumers complaining about the need to call multiple endpoints to get what they need it might be a good idea to explore graphql also if you are looking to build apis without needing to constantly push out new versions while maintaining older versions graphql is again a great choice that was actually all about graphql in this particular video hope this video was useful in some way if it was please do like and comment and also don't forget to subscribe to cs tracker and press the bell icon see you in the next video and stay safe
