What is GraphQL Query?
TL;DR
Read operation in GraphQL for fetching data from APIs with precise field selection and type safety.
GraphQL Query is a read operation that allows you to request exactly the data you need from an API. Unlike REST where you get fixed endpoints with predetermined data structures, GraphQL lets you specify precisely which fields you want, reducing over-fetching and under-fetching.
Basic Query Syntax:
query GetUser {
user(id: "123") {
id
name
posts {
title
createdAt
}
}
}
Real usage:
import { useQuery } from 'urql';
const UserQuery = `
query User($id: ID!) {
user(id: $id) {
id
name
avatar
}
}
`;
export function UserProfile({ userId }: { userId: string }) {
const [result] = useQuery({
query: UserQuery,
variables: { id: userId }
});
if (result.fetching) return <Loading />;
if (result.error) return <Error message={result.error.message} />;
return <div>{result.data.user.name}</div>;
}
Key Benefits:
- Precise data fetching: Request only what you need
- Type safety: TypeScript types generated from schema
- Single request: Fetch related data in one query
- No over-fetching: Reduce bandwidth usage
- Nested relations: Get deeply nested data easily
Query with Fragments:
fragment UserFields on User {
id
name
}
query GetUsers {
users {
...UserFields
}
}
AI-Friendly: GraphQL queries are declarative and self-documenting. AI tools understand the schema-based type system, can generate type-safe queries, suggest optimal field selections, and handle complex nested data fetching patterns efficiently.