GraphQL interview questions
23 questions with answers. 251 open jobs in India ask for GraphQL.
When and How to use GraphQL with microservice architecture?
Definitely approach #1.
Having your clients talk to multiple GraphQL services (as in approach #2) entirely defeats the purpose of using GraphQL in the first place, which is to provide a schema over your entire application data to allow fetching it in a single roundtrip.
Having a shared nothing architecture might seem reasonable from the microservices perspective, but for your client-side code it is an absolute nightmare, because every time you change one of your microservices, you have to update all of your clients. You will definitely regret that.
GraphQL and microservices are a perfect fit, because GraphQL hides the fact that you have a microservice architecture from the clients. From a backend perspective, you want to split everything into microservices, but from a frontend perspective, you would like all your data to come from a single API. Using GraphQL is the best way I know of that lets you do both. It lets you split up your backend into microservices, while still providing a single API to all your application, and allowing joins across data from different services.
If you don't want to use REST for your microservices, you can of course have each of them have its own GraphQL API, but you should still have an API gateway. The reason people use API gateways is to make it more manageable to call microservices from client applications, not because it fits well into the microservices pattern.
From Stack Overflow: asked by Fabrizio Fenoglio, answered by helfer (CC BY-SA 3.0)
In GraphQL what's the meaning of "edges" and "node"?
Let's begin with a short introduction in simple words
GraphQL Relay specifications
- mechanism for refetching an object
- description of how to page through connections
- structure around mutations to make them predictable
Connections:
a connection is a collection of objects with metadata such as
edges,pageInfo...pageInfo will contain
hasNextPage,hasPreviousPage,startCursor,endCursorhasNextPagewill tell us if there are more edges available, or if we’ve reached the end of this connection.
The array of records: edges
- edges will provide you flexibility to use your data(node)
- edges will help you for the pagination, There is GraphQL
GraphQLListbut with no functionality such as pagination, only with array of objects (data)
Each edge has
- a
node: a record or a data - a
cursor: base64 encoded string to help relay with pagination
- a
https://facebook.github.io/relay/graphql/connections.htm
Node:
- you can set the number of nodes you need to show using the relay
connectionArgs(first, last, after, before)
Relay Pagination works as
Fetches all objects in the collection and return a slice based on the
first/lastx records, used thru connectionArgsafter/beforeare used to indicate to the GraphQL server the number of required slice (data) using cursor from the node
There are many more things to consider like
nodeDefinitions,globalFieldId,nodeInterfaceshttps://github.com/graphql/graphql-relay-js#object-identification
From Stack Overflow: asked by Ska, answered by parwatcodes (CC BY-SA 4.0)
What's the point of input type in GraphQL?
From the spec:
The GraphQL Object type (ObjectTypeDefinition)... is inappropriate for re‐use [as an input], because Object types can contain fields that define arguments or contain references to interfaces and unions, neither of which is appropriate for use as an input argument. For this reason, input objects have a separate type in the system.
That's the "official reason", but there's several practical reasons why you can't use an object type as an input object type or use an object type as an input object type:
Functionality
Object types and input object types both have fields, however those fields have different properties that reflect how these types are used by the schema. Your schema will potentially define arguments and some kind of resolver function for an object type's fields, but these properties don't make sense in an input context (i.e. you can't resolve an input object's field -- it already has an explicit value). Similarly, default values can only be provided for input object type fields, and not object type fields.
In other words, this may seem like duplication:
type Student { name: String grade: Grade } input StudentInput { name: String grade: Grade }But adding features specific to either object types or input object types makes it clear that they behave differently:
type Student { name(preferred: Boolean): String grade: Grade } input StudentInput { name: String grade: Grade = F }Type system limitations
Types in GraphQL are grouped into output types and input types.
Output types are types that may be returned as part of a response produced by a GraphQL service. Input types are types that are valid inputs for field or directive arguments.
There's overlap between these two groups (i.e. scalars, enums, lists and non-nulls). However, abstract types like unions and interfaces don't make sense in an input context and cannot be used as inputs. Separating object types and input object types allows you to ensure that an abstract type is never used where an input type is expected.
Schema design
When representing an entity in your schema, it's likely that some entities will indeed "share fields" between their respective input and output types:
type Student { firstName: String lastName: String grade: Grade } input StudentInput { firstName: String lastName: String grade: Grade }However, object types can (and in reality frequently do) model very complex data structures:
type Student { fullName: String! classes: [Class!]! address: Address! emergencyContact: Contact # etc }While these structures may translate into appropriate inputs (we create a Student, so we also pass in an object representing their address), often they do not -- i.e. maybe we need to specify the student's classes by class ID and section ID, not an object. Similarly, we may have fields that we want to return, but don't want to mutate, or vice versa (like a
passwordfield).Moreover, even for relatively simple entities, we often have different requirements around nullability between object types and their "counterpart" input objects. Often we want to guarantee that a field will also be returned in a response, but we don't want to make the same fields required in our input. For example,
type Student { firstName: String! lastName: String! } input StudentInput { firstName: String lastName: String }Lastly, in many schemas, there's often not a one-to-one mapping between object type and input object type for a given entity. A common pattern is to utilize separate input object types for different operations to further fine-tune the schema-level input validation:
input CreateUserInput { firstName: String! lastName: String! email: String! password: String! } input UpdateUserInput { email: String password: String }All of these examples illustrate an important point -- while an input object type may mirror an object type some of the time, you're much less likely to see that in production schemas due to business requirements.
From Stack Overflow: asked by Dmitrii Dushkin, answered by Daniel Rearden (CC BY-SA 4.0)
What is the difference between Falcor and GraphQL?
I have viewed the Angular Air Episode 26: FalcorJS and Angular 2 where Jafar Husain answers how GraphQL compares to FalcorJS. This is the summary (paraphrasing):
- FalcorJS and GraphQL are tackling the same problem (querying data, managing data).
- The important distinction is that GraphQL is a query language and FalcorJS is not.
- When you are asking FalcorJS for resources, you are very explicitly asking for finite series of values. FalcorJS does support things like ranges, e.g.
genres[0..10]. But it does not support open-ended queries, e.g.genres[0..*]. - GraphQL is set based: give me all records where true, order by this, etc. In this sense, GraphQL query language is more powerful than FalcorJS.
- With GraphQL you have a powerful query language, but you have to interpret that query language on the server.
Jafar argues that in most applications, the types of the queries that go from client to server share the same shape. Therefore, having a specific and predictable operations like get and set exposes more opportunities to leverage cache. Furthermore, a lot of the developers are familiar with mapping the requests using a simple router in REST architecture.
The end discussion resolves around whether the power that comes with GraphQL outweighs the complexity.
From Stack Overflow: asked by Gajus, answered by Gajus (CC BY-SA 3.0)
What is an exclamation point in GraphQL?
That means that the field is non-nullable.
See more info in Graphql - Schemas and Types
From Stack Overflow: asked by JuanCaicedo, answered by Juan (CC BY-SA 4.0)
Are there any disadvantages to GraphQL?
Disadvantages:
- You need to learn how to set up GraphQL. The ecosystem is still rapidly evolving so you have to keep up.
- You need to send the queries from the client, you can just send strings but if you want more comfort and caching you'll use a client library -> extra code in your client
- You need to define the schema beforehand => extra work before you get results
- You need to have a graphql endpoint on your server => new libraries that you don't know yet
- Graphql queries are more bytes than simply going to a REST endpoint
- The server needs to do more processing to parse the query and verify the parameters
But, those are more than countered by these Advantages:
- GraphQL is not that hard to learn
- The extra code is only a few KB
- By defining a schema, you will prevent much more work afterwards fixing bugs and enduring hairy upgrades
- There are a lot of people switching to GraphQL so there is a rich ecosystem developing, with excellent tooling
- When using persistent queries in production (replacing GraphQL queries with simply an ID and parameters), you actually send fewer bytes than with REST
- The extra processing for incoming queries is negligible
- Providing a clean decoupling of API and backend allows for much faster iteration on backend improvenments
From Stack Overflow: asked by Dr.Nemo, answered by w00t (CC BY-SA 4.0)
Is it possible to not return any data when using a GraphQL mutation?
According to this Github issue you cannot return nothing.
You can define a return type which is nullable e.g.
type Mutation { addElement(element: ElementData): ID removeElement(id: ID): Boolean }But I suggest you return the id of the deleted element, because if you want to work with a cached store you have to update the store when the delete mutation has ran successfully.
From Stack Overflow: asked by angrykoala, answered by Locco0_0 (CC BY-SA 4.0)
Can graphql return aggregate counts?
You would define a new GraphQL type that is an object that contains a list and a number. The number would be defined by a resolver function.
On your GraphQL server you can define the resolver function and as part of that, you would have to write the code that performs whatever calculations and queries are necessary to get the aggregate counts.
This is similar to how you would write an object serializer for a REST API or a custom REST API endpoint that runs whatever database queries are needed to calculate the aggregate counts.
GraphQL's strength is that it gives the frontend more power in determining what data specifically is returned. Some of what you write in GraphQL will be the same as what you would write for a REST API.
From Stack Overflow: asked by orbital, answered by user9903 (CC BY-SA 3.0)
what's the difference between parseValue and parseLiteral in GraphQLScalarType?
The
serializemethod is called when the value of the type is going to be sent to the client as a response. Since the values on the output are JSON, the return value ofserializecould be anything. Could be string, number, array, object ...The other two methods (
parseValueandparseLiteral) are to read input.In GraphQL there are two ways of reading input from client, one is inline in the query, like:
query { allUsers(first:10) { id } }where
10is the inline value forfirstargument. Since the input language for GraphQL is not exactly JSON, the value (here10) is being parsed and converted to AST (Abstract Syntax Tree). In this case,parseLiteralcomes to play. It inputs the AST and returns the parsed value of the type. Types could be as complex as JSON andparseLiteralcould traverse the AST and return JSON.The other way of reading input from clients is through variables:
query ($howMany: YourCustomType) { users(first: $howMany) { id } }variables:
{ "howMany": { "thisMany": 10 } }Since the variables are pure JSON, you don't need AST here, you already have JSON. That's where
parseValuecomes to play. It gets the input as JSON and returns whatever the query resolver should use.function parseValue(value) { let first = value.thisMany; return first; }So, you could have different presentation when you read from variables than when you read values inline, but conceptually, they should be the same in terms of presentation. However since the "type" of input is different (inline is GraphQL and variable is JSON), the parsing algorithm could be different. That's why if you define it as input type, you need to provide two separate methods to read them.
From Stack Overflow: asked by MonkeyBonkey, answered by Aᴍɪʀ (CC BY-SA 4.0)
Can a GraphQL input type inherit from another type or interface?
No, the spec does not allow input types to implement interfaces. And GraphQL type system in general does not define any form of inheritance (the
extendskeyword adds fields to an existing type, and isn't for inheritance). The spec is intentionally constrained to stay simple. This means that you're stuck repeating fields across input types.That said, depending on the way you construct your schema, you could build some kind of type transformer that appends the common fields programmatically based on some meta-data, e.g. a directive. Here's one such implementation.
Better yet, you might be able to solve your problem via composition (always keep composition over inheritance in mind). E.g.
input Name { firstName: String lastName: String } input UserInput { name: Name password: String! } input UserChangesInput { name: Name id: ID! password: String }The client now has to send an object a level deeper, but that doesn't sound like much of a price for avoiding big repeating chunks. It might actually be good for the client as well, as they can now have common logic for building names, regardless of the query/mutation using them.
In this example, where it's only 2 simple fields, this approach is an overkill, but in general - I'd say it's the way to go.
From Stack Overflow: asked by kyrisu, answered by kaqqao (CC BY-SA 4.0)
What is the point of naming queries and mutations in GraphQL?
The query name doesn't have any meaning on the server whatsoever. It's only used for clients to identify the responses (since you can send multiple queries/mutations in a single request).
In fact, you can send just an anonymous query object if that's the only thing in the GraphQL request (and doesn't have any parameters):
{ user(id: 4) { id name profilePic(size: 200) } }This only works for a query, not mutation.
EDIT:
As @orta notes below, the name could also be used by the server to identify a persistent query. However, this is not part of the GraphQL spec, it's just a custom implementation on top.From Stack Overflow: asked by Nolan, answered by Petr Bela (CC BY-SA 4.0)
OData vs GraphQL
I have researched and also tried with Both GraphQL in Dot Net and Odata in DotNet Web API to create a working demo and What I found are
- Developer Usability Considering you have existing WebAPI(DotNet Framework) and want to migrate to GraphQL or OData compatible WebAPI then my answer is to choose OData because of its easy integration and Out of the Box Filter, OrderBy, Select, Expand, etc feature (Refer MSFT On DotNet OData). If you choose GraphQL then you have to do a lot of work like Create Type, Schema and Query and Implement Resolver for each query.
- Performance depends on your query logic. GraphQL and Odata Both have the capability to get what you request using $select in OData and in GraphQL you can request by their Query convention.
- API Development From Scratch, If you want only single endpoint for all API request and don't want to maintain versioning endpoint, Autosuggest field name and type of schema then GraphQL is the best option. But Availability of GraphQL Library for Each framework and Community varies for Technology stack(e.g. nodejs, C#, Ruby, Java etc)
Yes, I have reviewed and read article by Telerik which have described in detail. Comparision PDF For GraphQL and Odata I am attaching side by side comparison image only you can dig out detail in Reference link GraphQL vs OData.
Standard API
Here, No in API Versioning/ maintenance is positive meaning single endpoint and get rid of two versioned API
Query Capability
Surface Capability
Mainly OData service is used when you want to provide access to your database with minimal effort for CRUD Operation.
However if you aware about Sharepoint REST API and Office 365 REST API It is based on OData and provides a wide range of API. Now Microsoft is building universal API which is called Graph API or Microsoft Graph which by default enabled for CORS request and unified endpoints to Request from Office 365, dynamics 365, Outlook Exchange API, Onedrive API etc. Which are also supports OData.
From Stack Overflow: asked by Yar0myr, answered by anomepani (CC BY-SA 4.0)
What do 3 dots/periods/ellipsis in a relay/graphql query mean?
There are two uses of
...related to fragments.Incorporating a fragment by reference
query Foo { user(id: 4) { ...userFields } } fragment userFields on User { name }Has the effect of composing the fields from the fragment into the embedding query:
query Foo { user(id: 4) { name } }Note that fragments may compose other fragments.
Inline fragments
From the docs:
If you are querying a field that returns an interface or a union type, you will need to use inline fragments to access data on the underlying concrete type.
https://graphql.org/learn/queries/#inline-fragments
These can be used to compose fields in a type-dependent way. For example:
query Foo { profile(id: $id) { url ... on User { homeAddress } ... on Business { address } } }In this example, the server will determine whether to return the
homeAddressoraddressfield at runtime, based on whether the requested object is aUseror aBusiness.From Stack Overflow: asked by jbrown, answered by Greg Hurrell (CC BY-SA 4.0)
Can you make a graphql type both an input and output type?
In the GraphQL spec, objects and input objects are distinct things. Quoting the spec for input objects:
Fields can define arguments that the client passes up with the query, to configure their behavior. These inputs can be Strings or Enums, but they sometimes need to be more complex than this.
The Object type... is inappropriate for re‐use here, because Objects can contain fields that express circular references or references to interfaces and unions, neither of which is appropriate for use as an input argument. For this reason, input objects have a separate type in the system.
An Input Object defines a set of input fields; the input fields are either scalars, enums, or other input objects. This allows arguments to accept arbitrarily complex structs.
While an implementation might provide convenience code to create an object and a corresponding input object from a single definition, under the covers, the spec indicates that they'll have to be separate things (with separate names, such as
ReservationandReservationInput).From Stack Overflow: asked by MonkeyBonkey, answered by CommonsWare (CC BY-SA 4.0)
What is Over-Fetching or Under-fetching?
Over-fetching is fetching too much data, meaning there is data in the response you don't use.
Under-fetching is not having enough data with a call to an endpoint, forcing you to call a second endpoint.
In both cases, they are performance issues: you either use more bandwidth than ideal, or you are making more HTTP requests than ideal.
In a perfect world, these problems would never arise; you would have exactly the right endpoints to give exactly the right data to your products.
These problems often appear when you scale and iterate on your products. The data you use on your pages often change, and the cost to maintain a separate endpoint with exactly the right data for each component becomes too much.
So, you end up with a compromise between not having too many endpoints, and having the endpoints fit each component needs best. This will lead to over-fetching in some cases (the endpoint will provide more data than needed for one specific component), and under-fetching in some others (you will need to call a second endpoint).
GraphQL fixes this problem because it allows you to request which data you want from the server. You specify what you need and will get this data, and only this data, in one trip to the server.
From Stack Overflow: asked by Saber Alex, answered by yachaka (CC BY-SA 4.0)
The difference between Mutation and Query
Short
Conventionally:
Query— for querying data (SELECToperations)Mutation— for creating new and updating/deleting existing data (INSERT,UPDATE,DELETE)
Detailed
Technically any GraphQL query could be implemented to cause a data write. But there is a convention that any operations that cause writes should be sent explicitly via a mutation.
Besides the difference in the semantic, there is one important technical difference:
Queryfields can be executed in parallel by the GraphQL engine whileMutationtop-level fields MUST execute serially according to the spec:If the operation is a mutation, the result of the operation is the result of executing the mutation’s top level selection set on the mutation root object type. This selection set should be executed serially.
It is expected that the top level fields in a mutation operation perform side‐effects on the underlying data system. Serial execution of the provided mutations ensures against race conditions during these side‐effects.
Source: https://graphql.github.io/graphql-spec/draft/#sec-Mutation
From Stack Overflow: asked by Malakai, answered by RomanHotsiy (CC BY-SA 4.0)
Does apollo-client work on node.js?
Apollo Client should work just fine on Node. You only have to install cross-fetch.
Here is a complete TypeScript implementation of Apollo Client working on Node.js.
import { ApolloClient, gql, HttpLink, InMemoryCache } from "@apollo/client"; import { InsertJob } from "./graphql-types"; import fetch from "cross-fetch"; const client = new ApolloClient({ link: new HttpLink({ uri: process.env.PRODUCTION_GRAPHQL_URL, fetch }), cache: new InMemoryCache(), }); client.mutate<InsertJob.AddCompany, InsertJob.Variables>({ mutation: gql`mutation insertJob($companyName: String!) { addCompany(input: { displayName: $companyName } ) { id } }`, variables: { companyName: "aaa" } }) .then(result => console.log(result));From Stack Overflow: asked by Ed Staub, answered by Andre Pena (CC BY-SA 4.0)
When should I use a Relay GraphQL connection and when a plain list?
Connections
- More powerful and flexible than simple lists.
- Support pagination (forward and back), with cursors.
- Fine-grained mutation support (eg.
RANGE_ADD,RANGE_DELETE,NODE_DELETE, as described in the guide). - Requires a
firstorlastargument in order to limit the size of the result set. - Has an
edgesfield that provides a place to locate per-edge, edge-specific data. - A heavier-weight concept, requiring more work to define in the schema.
Lists
- Simple and lightweight.
- No support for pagination (the entire list is always returned).
- No special mutations features for prepending, appending etc (although it is a requested feature).
Which to use?
- Whenever you need pagination, you should use a connection.
- If you need fine-grained control over mutations, you may choose to use a connection, even if you don't need pagination.
- If you want all the items in a connection, you can use
firstwith some large number. - If you want to expose a short list with minimal effort, use a simple list.
From Stack Overflow: asked by Greg Hurrell, answered by Greg Hurrell (CC BY-SA 3.0)
What is the difference between useQuery and useLazyQuery in Apollo graphQL?
When
useQueryis called by the component, it triggers the query subsequently.But when
useLazyQueryis called, it does not trigger the query subsequently, and instead return a function that can be used to trigger the query manually. It is explained on this page: https://www.apollographql.com/docs/react/data/queries/#manual-execution-with-uselazyqueryWhen React mounts and renders a component that calls the
useQueryhook, Apollo Client automatically executes the specified query. But what if you want to execute a query in response to a different event, such as a user clicking a button? TheuseLazyQueryhook is perfect for executing queries in response to events other than component rendering. This hook acts just likeuseQuery, with one key exception: whenuseLazyQueryis called, it does not immediately execute its associated query. Instead, it returns a function in its result tuple that you can call whenever you're ready to execute the query.From Stack Overflow: asked by Lionel George, answered by Kevin Myat (CC BY-SA 4.0)
How can I query all the GraphQL type fields without writing a long query?
Unfortunately what you'd like to do is not possible. GraphQL requires you to be explicit about specifying which fields you would like returned from your query.
From Stack Overflow: asked by BlackSigma, answered by Peter Horne (CC BY-SA 3.0)
Get GraphQL whole schema query
Update
Using
graphql-cliis now the recommended workflow to get and update your schema.The following commands will get you started:
# install via NPM npm install -g graphql-cli # Setup your .graphqlconfig file (configure endpoints + schema path) graphql init # Download the schema from the server graphql get-schemaYou can even listen for schema changes and continuously update your schema by running:
graphql get-schema --watchIn case you just want to download the GraphQL schema, use the following approach:
The easiest way to get a GraphQL schema is using the CLI tool get-graphql-schema.
You can install it via NPM:
npm install -g get-graphql-schemaThere are two ways to get your schema. 1) GraphQL IDL format or 2) JSON introspection query format.
GraphQL IDL format
get-graphql-schema ENDPOINT_URL > schema.graphqlJSON introspection format
get-graphql-schema ENDPOINT_URL --json > schema.jsonor
get-graphql-schema ENDPOINT_URL -j > schema.jsonFor more information you can refer to the following tutorial: How to download the GraphQL IDL Schema
From Stack Overflow: asked by Aleksandrenko, answered by schickling (CC BY-SA 4.0)
GraphQL Expected Iterable, but did not find one for field xxx.yyy
I ran into this problem as well. It appears that what you're returning from your resolver doesn't match the return type in your schema.
Specifically for the error message
Expected Iterable, but did not find one for field library.user., your schema expects an array(Iterable) but you aren't returning an array in your resolverI had this in my schema.js:
login(email: String, password: String): [SuccessfulLogin]I changed that to:
login(email: String, password: String): SuccessfulLoginNotice the square brackets around "SuccessfulLogin". It's up to you whether you want to update the resolver return type or update the schema's expectations
From Stack Overflow: asked by Vetterjack, answered by Vineeth Pradhan (CC BY-SA 4.0)
How to send graphql query by postman?
There's a better way to do it using the REST client Insomnia
Docs are here, how to send graphql queries: https://support.insomnia.rest/article/61-graphql
Below are the steps for postman
Step 1.
Run the GraphiQL in Chrome, open the Chrome Dev Console, click the Network tab, and make the query from graphiql, when you make the query, network tab will show the graphql request...
Step 2.
From the
graphqlrequest copy the request query, Select theCopy as cURL (cmd)Step 3.
Open Postman, In the Top-Left click on the
Importbutton, after you clickImportyou have to click thePaste Raw Text, and paste the copiedcURLrequest as done in step2 after it's done click theImportStep 4.
Postman is ready to send the Graphql request, Just Click on the
SendButton, you will see theResponsein the Response Box in body as belowStep 5.
To see how the query is being sent click on the
Bodytab next toHeaders, you will get know how to provide the fields from postman in JSON format.e.g:
edges {\n node {\n id\n jobId\n }\n, If you want to view another field then you need to add it in with the suffix\nlike if need
namethen :edges {\n node {\n id\n jobId\n name\n }\n\nhere just means to represent a new line. Instead, you can make it simpler by providing a clear and illustrative JSON like below===========================================================================
Note: The body type must be raw with
application/jsoncontent-type. So, the query must be a valid JSON with quotes".."{ "query":"{viewer {user {edges {node {id jobId name }}}}}" }===========================================================================
you can directly start from
step 5if you know how to send the query in body and other things too that needs to be required while making a request from postmanWith simplified JSON
From Stack Overflow: asked by ZPPP, answered by parwatcodes (CC BY-SA 4.0)
Related topics
Where these questions come from
Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.
- Stack Overflowby its contributors, named on each answerCC BY-SA23 questions