GraphQL Queries, Mutations & Subscriptions
GraphQL Queries, Mutations & Subscriptions in Modern JavaScript
While REST APIs require multiple round-trips to disparate endpoints (/users/1, /users/1/orders, /users/1/posts) leading to over-fetching or under-fetching, GraphQL allows clients to request exactly the data they need in a single query.
1. The Three Operations of GraphQL
- 1Query: Read-only data retrieval (analogue to HTTP
GET). - 2Mutation: Data writes, updates, and deletes (analogue to
POST,PUT,DELETE). - 3Subscription: Real-time event streams powered by WebSockets.
2. Executing Queries with Native Fetch
GraphQL does not require heavy client libraries (like Apollo Client) for basic needs. All queries execute as standard HTTP POST requests to a single /graphql endpoint:
3. Executing Mutations
Mutations modify server state and return the updated fields in the same operation:
4. Real-Time Subscriptions via WebSockets
Subscriptions use WebSockets (using protocols like graphql-transport-ws) to receive streaming updates when mutations occur on the server:
5. Critical Gotcha: HTTP Status Codes in GraphQL
Unlike REST, GraphQL almost always returns HTTP status 200 OK, even when an error occurs in resolver execution! Always check the response body's errors array:
Practice Quiz
JSON.stringify Replacer & JSON.parse Reviver
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Fetch Interceptors & Request Middleware | JSON.stringify Replacer & JSON.parse Reviver |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.