What is GraphQL?
GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understand description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.
QL stands for query language which means query language. It can be understood like an SQL query, but not on the Table, but on the APIs (query language for APIs – you can understand more through the example in ⬇️). It is not a technology to replace REST API but more like a library to help overcome REST problems.
1. History of GraphQL
- REST API was born in 2000, is a common standard of software development, web programming. Combined with HTTP methods GET, POST, PUT, DELETE.
- GraphQL was born in 2015 developed by Facebook and open-sourced in 2017 and is growing rapidly. GraphQL was born not to replace REST, it is an add-on library for REST. You can use a combination of GraphQL and REST.
2. Advantages of GraphQL
- Being able to get exactly the data that the Client needs through the query helps to improve, improve the query speed, avoid unnecessary data redundancy: For example, in a normal REST API, it will return possible results. surplus or lack. For example, singer Mono wants to get more song title Waiting for you , usually we have to edit the API to get more information about the song.
- For GraphQL we just need to add the information we need to get as follows:
- This saves and reuses our APIs which saves the development process of building the Backend.
3. Example
Nodejs environment, JavaScript.
- Setting
1 2 3 | npm init npm install graphql --save |
- Create the file index.js as follows
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | //Import các thư viện cần dùng var express = require('express'); var { graphqlHTTP } = require('express-graphql'); var { buildSchema } = require('graphql'); // Xây dựng một Schema, sử dụng ngôn ngữ Schema GraphQL var schema = buildSchema(` type Query { author: String, song:String } `); // Root cung cấp chức năng phân giải cho mỗi endpoint API var root = { author: () => { return 'Mono'; }, song: () => { return 'Waiting for you!'; }, }; //Tạo server với express var app = express(); //Khai báo API graphql app.use('/graphql', graphqlHTTP({ schema: schema, rootValue: root, graphiql: true, //sử dụng công cụ GraphiQL để đưa ra các query GraphQL theo cách thủ công })); // Khởi tạo server tại port 4000 app.listen(4000); console.log('Running a GraphQL API server at http://localhost:4000/graphql'); |
- Run :
1 2 | node index.js |
Query postman or on http://localhost:4000/graphql (built-in tool, directly queryable here).
4. Conclusion
- This is a very useful technology. You should try applying it to your project. 🔗link for detail: https://graphql.org/graphql-js/