GraphQL Flashcards
(10 cards)
What is GraphQL, and how does it differ from REST?
GraphQL is a query language for APIs, allowing clients to request specific data. Unlike REST’s fixed endpoints, GraphQL uses a single endpoint with flexible queries.
What is a GraphQL schema?
A schema defines the API’s data structure and operations. Example: type User { id: ID!, name: String }
specifies a User type with required ID and optional name.
How do you write a GraphQL query?
”```graphql
query {
user(id: 1) {
id
name
}
}
//Explanation: Requests specific fields for a user with ID 1.
How do you handle authentication in GraphQL?
Pass JWT in headers, verify in resolvers. Example: context: ({ req }) => { const user = verifyToken(req.headers.authorization); return { user }; }
adds user to context.
What are GraphQL subscriptions?
Subscriptions enable real-time updates via WebSockets. Example: subscription { messageAdded(channelId: "1") { content } }
listens for new messages.
How do you optimize GraphQL queries to prevent over-fetching?
Use DataLoader to batch and cache requests. Example: new DataLoader(keys => db.batchUsers(keys))
reduces database calls for user queries.
What is the N+1 problem in GraphQL, and how do you solve it?
N+1 problem occurs when resolving N items triggers N additional queries. Solve with batching via DataLoader. Example: Batch user queries instead of fetching each individually.
What is a GraphQL resolver?
A resolver is a function that fetches data for a field. Example: user: (parent, args) => db.findUserById(args.id) retrieves user data from a database.”
How do you set up a GraphQL server with Apollo?
``javascript const { ApolloServer, gql } = require(‘apollo-server’); const typeDefs = gqltype Query { hello: String }; const resolvers = { Query: { hello: () => ‘Hello’ } }; const server = new ApolloServer({ typeDefs, resolvers }); server.listen(); // Explanation: Defines schema and resolvers, starts server on localhost.
What is a GraphQL mutation, and how is it used?
A mutation modifies server-side data. Example: mutation { createUser(name: "Alice") { id name } }
creates a user and returns their data.”