GraphQL is a query language for APIs developed by the Facebook team. This language 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. Facebook open sourced it in 2015.
A GraphQL request can be either a query (read operation) or a mutation (write operation). For both cases, the request is a simple string that a GraphQL service can interpret, execute, and resolve with data in a specified format.
Main features of GraphQL are:Retrieve only the data your client needs in a single request - No over-fetching:
Send a GraphQL query to your API with the fields you want to fetch and get only that set of fields in return. Apps using GraphQL are fast and stable because they control the data they get, not the server.
Get many resources in a single round-trip:We can create queries with a different combination of datasets which will avoid multiple requests to fetch required data, thereby eliminating overheads.
Describe what’s possible with a type system:GraphQL APIs have a single endpoint and it organizes API with requesting types and fields.
Evolve your API without versions - maintainability:Add new fields and types to your GraphQL API without impacting existing queries. Aging fields can be deprecated and hidden from tools. By using a single evolving version, GraphQL APIs give apps continuous access to new features and encourage cleaner, more maintainable server code.
GraphQL Queries:Here’s an example of a GraphQL query that a client can use to ask a server about the name and email of user #1:
1 2 3 4 5 6 7 |
|
1 2 3 4 5 6 7 8 9 |
|
Here we are assuming, we have an existing ROR application with model Article and fields title and body.
You can install graphql from RubyGems by adding to your application’s Gemfile:1 2 3 |
|
Now you can get started with a few GraphQL generators:
1
|
|
- Set up a folder structure in app/graphql/
- Add schema definition
- Add a query type definition
- Add a route and controller for executing queries After installing you can see your new schema by:
1 2 3 |
|
Here I am building by hand.
Define some types: Add article_type.rb in ‘types’ folder which will define ArticleType1 2 3 4 5 6 7 |
|
1 2 3 4 5 6 7 8 9 10 11 |
|
1 2 3 4 |
|
1 2 |
|
Here’s an example of a GraphQL query that a client can use to ask a server about the title of article #1:
1 2 3 4 5 |
|
1 2 3 4 5 6 7 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|