scieee AI-readable full text Open interactive document viewer

Implementing graphql in existing REST api

Lama, Binod

Abstract

Classpip is the application developed by the student and professor of EETAC . The concept of classpip is based the principle of gamification which uses the gaming principle to the non-gaming context. Classpip applies the concept of gamification into education systems. The whole project of class pip is divided into 3 main parts: classpip dashboard which is the web application for desktop, classpip mobile is for the android /IOS devices and the classpip service which serves as the backend for these two clients. The main objective of this project is to improve the data fetching process by implementing Graphql. The whole work is done to implement graphql on top of existing rest api which uses a framework call loopback .We have tried various graphql architecture which can help improve the overall process of data fetching from the database. Graphql was developed by Facebook whose main goal is to increase the performance of the mobile users because in Graphql we only get what we need in just one request which saves the bandwidth and the time to load that data. Popular software companies like GitHub, Instagram, Twitter, Stack Share and more has already implemented graphql .

Full text

TREBALL FINAL DE GRAU TÍTOL DEL TFG: Implementación de Graphql en la REST API existente TITULACIÓ: Grau en Enginyeria de Sistemes de Telecomunicació AUTOR: Binod Lama DIRECTOR: Miguel Valero García DATA: 24 de octubre 2019 Títol: Implementing Graphql in Existing REST API TITULACIÓ: Grau en Enginyeria de Sistemes de Telecomunicació Autor: Binod Lama Director: Miguel Valero Gracia Data: 24 de Octubre 2019 Resum Classpip es la aplicación desarrollada por el alumno y profesor de EETAC. El concepto de classpip se basa en el principio de la gamificación, que utiliza el principio del juego en el contexto no relacionado con el juego. Classpip aplica el concepto de gamificación en los sistemas educativos. Todo el proyecto de class pip se divide en 3 partes principales: tablero de classpip que es la aplicación web para escritorio, classpip mobile es para dispositivos Android / IOS y el servicio classpip que sirve como back-end para estos dos clientes. El objetivo principal de este proyecto es mejorar el proceso de obtención de datos mediante la implementación de Graphql. Todo el trabajo se realiza para implementar graphql además de la API de REST existente que usa un loopback de llamada de marco. Hemos probado varias arquitecturas de graphql que pueden ayudar a mejorar el proceso general de recuperación de datos desde la base de datos. Graphql fue desarrollado por Facebook, cuyo objetivo principal es aumentar el rendimiento de los usuarios de dispositivos móviles porque en Graphql solo obtenemos lo que necesitamos en una sola solicitud que ahorra el ancho de banda y el tiempo para cargar esos datos. Las compañías de software populares como GitHub, Instagram, Twitter, Stack Share y más ya han implementado graphql. Title: Implementing Graphql in Existing REST API Degree: Telecommunications systems Engineering Author: Binod Lama Director: Miguel Valero Gracia Date: Octuber 24 2019 Overview Classpip is the application developed by the student and professor of EETAC . The concept of classpip is based the principle of gamification which uses the gaming principle to the non-gaming context. Classpip applies the concept of gamification into education systems. The whole project of class pip is divided into 3 main parts: classpip dashboard which is the web application for desktop, classpip mobile is for the android /IOS devices and the classpip service which serves as the backend for these two clients. The main objective of this project is to improve the data fetching process by implementing Graphql. The whole work is done to implement graphql on top of existing rest api which uses a framework call loopback .We have tried various graphql architecture which can help improve the overall process of data fetching from the database. Graphql was developed by Facebook whose main goal is to increase the performance of the mobile users because in Graphql we only get what we need in just one request which saves the bandwidth and the time to load that data. Popular software companies like GitHub, Instagram, Twitter, Stack Share and more has already implemented graphql . INDEX INTRODUCTION ................................................................................................ 9 CHAPTER 1. APPLICATION PROGRAMMING INTERFACE ........................ 10 1. Application Programming Interface .............................................................................. 10 1.1.1. Rest API ................................................................................................................ 10 1.1.2. Limitation of REST API ......................................................................................... 11 1.2. Graphql API ...................................................................................................................... 12 1.2.1. Schema ................................................................................................................. 13 1.2.2. Resolver ................................................................................................................ 13 1.2.3. Create Graphql server .......................................................................................... 14 1.2.4. Limitations of Graphql ........................................................................................... 17 CHAPTER 2. ADVANTAGE OF USING GRAPHQL OVER REST ................. 18 2.1. Eliminate under and over data fetching. .......................................................................... 18 2.2. Has strong schema type .................................................................................................... 20 2.3. Schema stitching ................................................................................................................ 20 2.4. Rapid Product Iterations on the Frontend ....................................................................... 20 2.5. Graphql has Rich open-source ecosystem ..................................................................... 20 CHAPTER 3. POPULAR GRAPHQL ARCHITECTURE ................................. 21 CHAPTER 4. GRAPHQL ARCHITECTURE IMPLEMENTED TO REST ........ 23 4.1. Replacing the existing REST with Graphql server ......................................................... 23 4.2. Graphql as a gateway between REST and the client ...................................................... 24 CHAPTER 5. IMPLEMENT GRAPHQL IN EXISTING REST API ................... 25 5.1. Analyze the data model of the REST API ......................................................................... 25 5.2. Generate Graphql schema based on data model. .......................................................... 25 5.3. Implement resolver functions for the schema. ............................................................... 25 CHAPTER 6. IMPLEMENT GRAPHQL IN CLASSPIP SERVICE ................... 26 6.1. Graphql as the gateway architecture: .............................................................................. 26 CHAPATER 7. PREFORMANCE TEST .......................................................... 29 7.1. Scenario 1: Get the student name and school information ........................................... 29 7.2. Scenario 2: Get the student, school, rewards, point relation: ....................................... 31 CHAPTER 8. CONSUME GRAPHQL IN CLASSPIP DASHBOARD .............. 33 8.1. To display /groups pages: ................................................................................................. 33 8.2. To display /groupStudents/ page: .................................................................................... 36 8.1.2. Create new collectionCards ........................................................................................... 40 CHAPTER 9. CONCLUSION ........................................................................... 42 REFERENCES ................................................................................................. 43 UNDERGRADUTE THESIS PROJECT 9 INTRODUCTION As the world of application Program interface (API) is evolving every day with the growing internet technology we need to get updated our applications with it. As the new technology comes that doesn't mean they are right to use in every scenario. We need to analyze their capabilities and use them as our needs. Graphql is also a new evolving technology that lets rethink the developers how to build the client and API web applications. Graphql is a query language for APIS which lets client to fetch data from database in an efficient way without wasting any bandwidth. It lets the client specify exactly what data it needs. We need to think Graphql as a tool to build our application. Before we implement Graphql in our project we need to rethink the cost of implementation and how it will help to grow our applications. Classpip is a web application developed by the professors and the students of EETAC. It was started back in 2016. It is a server-based application that needs to interact with server to get its data. The main project of Classpip is divided into three parts: ClassPip Dashboard which is for the desktop web apps, Classpip Mobile and the Classpip Service which serves as a REST API for our desktop and Mobile clients. The main objective of this document is to explain the process of implementation of Graphql which can be useful for fetching the data. As the service of Classpip uses a framework called strong loopback which is based on REST architectural style, Web services. The project documentation is divided in 9 different chapters. In Chapter 1 we will briefly introduce the Api. This chapter will explain the core concept of API and how api world works. In the second chapter we will briefly compare the concept of REST and Graphql. In this chapter we will explain the advantages of graphql. In the third and the fourth chapter we will explain about the different architecture that can be used to implement Graphql with some examples. In chapter 5 and 6 we will finally explain the process of creating a new Graphql server and implement in Classpip dashboard. In these chapter we will explain how and why Graphql should be implemented in the coming future to increase the efficiency of our application classPip. In chapter 7 you can find about the performance test between rest and graphql. We have created some scenario to test their performance. In chapter 8 we have explained about the process of implementation of graphql in Classpip dashboard which is based on angular. Finally, in the last chapter we will provide the conclusion over this project. . UNDERGRADUTE THESIS PROJECT 16 Fig. 5 Executing query in graphql playground to get the task information In Figure 5 we have defined the query in the left side and in the right is the response of that query which the task information. Fig. 6 Executing query in graphql playground to get list of tasks In figure 6 we can see how we can execute tasks query; the response is the list tasks in Json format. Similarly, we can execute the query for users to get an array of users and user by user id. UNDERGRADUTE THESIS PROJECT 17 1.2.4. Limitations of Graphql Some of drawbacks of Graphql are explain below: 1.Caching Overall the idea of cache is to lower down the server work by saving the data in client side for repetitive same request. As we only have post request in Graphql, which means we cannot cache those post request. We need to use different libraries to overcome this problem or set the global unique Ids. 2.Error handling As queries always returns http status code 200 despite that query was unsuccessful which makes it more complex while handling errors. 3.Performance As we can send the nested query which means it needs time to process all the data. So, we should keep in mind the limitation of nesting in particular query to improve our application performance. UNDERGRADUTE THESIS PROJECT 18 Chapter 2. ADVANTAGE OF USING GRAPHQL OVER REST Some of the advantages of using Graphql over Rest are briefly described below 2.1. Eliminate under and over data fetching. As in the above example of user and task Graphql project we can send customized query to get the task information along with the username and id just in one request. Fig. 7 Example of nested query In figure 7 we have defined a query where we will get the list of tasks along with user’s id and username. The response of this query is shown in figure 8 . UNDERGRADUTE THESIS PROJECT 19 Fig. 8 response of the nested query We can include only the needed fields to get the response from the server and it’s just needing to request one we can get what we want. But in Rest we need to send multiple request because one request is not enough to get all the required information, and we also get unwanted data which will increase the payloads and decreases the overall performance of the application. UNDERGRADUTE THESIS PROJECT 20 2.2. Has strong schema type Graphql schemas are the backbone of every Graphql API. Documentation can be generated automatically which will help the developer’s life to be simpler otherwise they need to be created manually. 2.3. Schema stitching We can connect and merge multiple Graphql api which means clients can connect to multiple api just by using single api. Graphql bindings take the idea of schema stitching to the next level by enabling a simple approach to reuse and sharing Graphql APIs. 2.4. Rapid Product Iterations on the Frontend As we add new function in frontend we need different types of data. In Graphql they can send custom query to get those data which means they don’t need to inform backend every time that they need certain types of data which can significantly increase the efficiency of overall work. 2.5. Graphql has Rich open-source ecosystem As Graphql is used by most of the software companies like GitHub, Facebook (which created the Graphql) many tools are developed day by day which will certainly help to make Graphql a better api language. UNDERGRADUTE THESIS PROJECT 21 Chapter 3. POPULAR GRAPHQL ARCHITECTURE Some of the popular graphql Architecture in real world application are described below: 1: Graphql directly connected to database. In this architecture graphql is responsible to fetch data directly from the database which is shown in figure 9 . Fig. 9 Architecture (source:https://www.howtographql.com/basics/3-big-picture/) 2: Graphql server as a layer between third party. Graphql act as a gateway to different services or to the database or may be to the different REST api which is shown in the figure10. Fig.10 Architecture (source:https://www.howtographql.com/basics/3-big- picture/) UNDERGRADUTE THESIS PROJECT 22 3: Hybrid approach which means it is connected to a database and different services and different rest api which is shown in figure 11. Fig. 11 Architecture (source:https://www.howtographql.com/basics/3-big- picture/) UNDERGRADUTE THESIS PROJECT 23 CHAPTER 4. GRAPHQL ARCHITECTURE IMPLEMENTED TO REST To implement graphql in our service class pip we have used the following two architecture which are replacing existing REST with graphql completely and Graphql as thin layer in between REST and the client. 4.1. Replacing the existing REST with Graphql server Fig. 12 Replacing REST with Graphql To implement the above architecture shown in fig 12 we need to change the following things: In Server side: Create graphql server and connect to database. In Client side: Change all the data fetching methods by using graphql query. Some of the Advantages of this architecture are listed below: 1.No need to map every Rest api endpoint 2. Can configure graphql to obtain the nested and complex data type which needs multiple data fetching if we use Rest. Some of the disadvantages of this architecture are listed below: 1.Difficult to connect with existing databases (Database fields mismatch) 2. Needs to reconfigure all the data fetching process in Client side which means a lot works in frontend side. UNDERGRADUTE THESIS PROJECT 24 4.2. Graphql as a gateway between REST and the client Fig.13 Graphql as gateway To implement the above architecture shown in figure 13 we need to change the following things: configuration: In server: Create graphql server and map the rest endpoint In client: Fetch the required complex data using graphql. Some of the Advantages of this architecture are listed below: - No need to configure database - No need to change the current architecture and least work we can use the power of graphql. - Can be extended in future for new functionality - Graphql and rest can work side by side - Can configure graphql to obtain the nested and complex data type which needs multiple data fetching if we use Rest. Some of the disadvantages of this architecture are listed below: • Manually map the rest endpoints which can be complex. UNDERGRADUTE THESIS PROJECT 25 CHAPTER 5. IMPLEMENT GRAPHQL IN EXISTING REST API In the following simple steps described below we can implement Graphql to our classPip easily: 5.1. Analyze the data model of the REST API At first, we need to understand the data models of REST API. Basically, we need to know what the fields and their relationships are. 5.2. Generate Graphql schema based on data model. Once we understood the data model we can start creating Graphql schema. AS there are different approaches to create our schema, some of them are listed below: 1.Manully We can create the schema of our graphql server manually. This approach may be simple for the small project but for the large and complex data model it's difficult to create all the schema manually. 2.Using Prisma to create schema automatically. We can use Prisma to create our graphql schema automatically. Prisma is a database attraction layer that turn database into graphql api. It is glue in between our database and the graphql server. With Prisma we can create automatically the CURD based Schema for our graphql. 5.3. Implement resolver functions for the schema. Once the schemas are defined we need to write the resolver functions for it. How to write the resolver function which can be found in chapter 7. UNDERGRADUTE THESIS PROJECT 32 Fig. 21 Graphql query and response Total time consumed: 527ms, Total size:1.57 KB UNDERGRADUTE THESIS PROJECT 33 CHAPTER 8. CONSUME GRAPHQL IN CLASSPIP DASHBOARD To consume the graphql implemented api in classpip dashboard we just need to send post request to a graphql api to get what we need. For demonstration how to consume a graphql api for our Classpip dashboard we have implemented two pages in which we need to fetch the information about groups and the students 8.1. To display /groups pages: Data needed to display the /groups pages are list of Group names with group grade names and group matter names. Fig. 22 Groups page in classpip dashboard Rest implementation: When a groups page is clicked then it needs to call 3 different endpoints to get all the required information: a. Get localhost:3000/api/groups where we will get the list of group id, group name, schoolId, teacherId, gradeId and matterId. UNDERGRADUTE THESIS PROJECT 34 Fig. 23 Response list of groups b. Get localhost:3000/api/groups/{id}/matters where we get the group matters name, id and schoolId. To get the information of whole groups matters information we need to call N times the number of Group. Fig. 24 Rest response of groups matter. c. Get localhost:3000/api/groups/{id}/grades where we will get the groups grades name, id and schoolId. To get the information of whole groups grades information we need to call N times the number of Group. UNDERGRADUTE THESIS PROJECT 35 Fig. 25 Rest response of groups grade. Graphql Implementation: We just send a post request where the body contains our query as a string. Even if the query includes child’s object the total number of requests is only one time to get all the necessary information to display the /group page. Fig. 26 Code to fetch data in classpip dashboard from graphql server UNDERGRADUTE THESIS PROJECT 36 Fig. 27 Query response with all the group information to display the group page From the figure 26 and 27 we can see that we just send a query with required fields to display the group page and the response is only what we have defined in query filed in just one http request. Whereas in figure 23 ,24, and 25 we can see that we need to send multiple request to REST api to display the same page and needs to do multiple trip cause just one request is not enough. 8.2. To display /groupStudents/ page: Figure 28 shows the groupstudents pages of group 1 When a group folder is clicked then it shows the list of students of that group with its student name, last name, email and their avatar image: UNDERGRADUTE THESIS PROJECT 37 Fig. 28 GroupStudents pages Rest implementation: To show this information we need to call these endpoints: a. Get localhost:3000/api/groups/{id}/students where we will have the list of student’s information in that particular group. Fig. 29 List of students from REST Figure 29 is the response of the localhost:3000/api/groups/{id}/students. UNDERGRADUTE THESIS PROJECT 38 b. GET request to localhost:3000/api/students/{studentId}/avatar where we will get the students avatar information like name, id and image URL. To get the full students avatar information we need to call N times the number of students in that group. Fig. 30 Avatar information of a student whose id is 10000 Figure 30 show the response of localhost:3000/api/students/{studentId}/avatar Graphql implementation: To display the /groupstudents page, we include our query as string in our post request where we have defined required fields to display that page. Fig. 31 Group query implementation in classPip Dashboard UNDERGRADUTE THESIS PROJECT 39 Fig. 31 Response of the above query In figure 28 and 29 we can see that we need to send multiple request to REST api to display the groupstudent page and needs to do multiple trip cause just one request is not enough. From the figure 30 and 31 we can see that we just send a nested query with required fields to display the groupStudents page and the response is only what we have defined in query filed in just one http request. UNDERGRADUTE THESIS PROJECT 40 8.1.2. Create new collectionCards Fig.32 Form to create new collection card. Figure 32 shows the form to create new collection card which was taken from classpip dashboard. To create the new collection cards, we have tested one using rest and another using graphql which is shown below: Rest implementation: We sent a post request with the information of new collectionCards where in the post body we define the required information about the new cards which is shown in figure 33. Fig. 33 Post request to create a new collection card UNDERGRADUTE THESIS PROJECT 41 Graphql implementation: To create the new collection cards using Graphql we send our query in a post body which is shown in the figure 34 where we need to send the mutation with required information to create the new collection card. Fig. 34 Graphql query implement in classpip