What is a GraphQL Query?
A GraphQL query is the request that we send to the server to get back only the required fields in the response. It allows us to fetch only the required data from the API, unlike the REST architecture, which gives us limited control over the data that we want to receive, and rather sends the entire data, regardless of its usage on the client side.
In GraphQL Queries, we specify exactly the data we need from the server, and the server fetches the data from the DB and returns exactly those fields that the client requested, hence saving on a lot of network bandwidth, and the response time.
In the below Query examples, we will use the below GraphQL endpoint in the GraphQL Playground –
https://studio.apollographql.com/public/countries/variant/current/explorer
A GraphQL Query consists of fields that the user wants to be present in the final data from the server. Let’s look at an example Query below.
Javascript
query { country(code: "BR" ) { name currency languages { code name } } } |
In the above query
- country(code: “BR”) : It represents the root field of the query that requests the data belonging to a Country entity “BR” from the server.
- name, currency : They represent the respective fields of the Country object that will be returned as the Query response.
- code, and name : They represent the nested fields present in the languages entity of the Country object.
Output:
The output of the above query will look like below
What is GraphQL Queries
GraphQL is a powerful open-source Query Language for APIs. It is most commonly known for its single endpoint query which allows the user to define a single endpoint to fetch all the information needed.
Queries in GraphQL allow us to retrieve the data from an API endpoint, and the data is what we specify in the query itself. In this article, we will learn about GraphQL Queries, and we will create some ourselves.