GraphQL vs REST: Key Differences Explained

Definition

GraphQL is an open-source query language for APIs and a runtime for executing those queries against your data. Created by Facebook in 2012 (publicly released in 2015), it was designed to address the limitations of traditional REST APIs—most notably over-fetching (receiving more data than needed) and under-fetching (needing multiple requests to get all required data). Unlike REST, GraphQL lets clients request exactly the data they need, in the structure they need it, with a single API call.

Core Characteristics

  1. Client-Driven Data FetchingThe client defines the shape of the response in the query, so the server returns only the requested fields (no more, no less). For example, if a client only needs a user’s name and email (not address or phone), it can specify just those fields, and the server will omit the rest.
  2. Single EndpointUnlike REST (which uses multiple endpoints for different resources, e.g., /users/posts/comments), GraphQL typically uses a single HTTP endpoint (e.g., /graphql) for all operations (queries, mutations, subscriptions).
  3. Strong TypingEvery GraphQL API is defined by a schema (a contract between client and server) that specifies all available types, fields, and operations. The schema enforces data types (e.g., StringIntBoolean, custom types like User), ensuring valid requests and predictable responses.
  4. Three Core Operations
    • Query: Read-only operation to fetch data (equivalent to HTTP GET in REST).
    • Mutation: Write operation to create/update/delete data (equivalent to HTTP POST/PUT/DELETE).
    • Subscription: Real-time operation to receive continuous updates (uses WebSockets instead of HTTP).
  5. IntrospectionGraphQL APIs are self-documenting: clients can query the API’s schema directly to discover available types, fields, and operations (e.g., using tools like GraphiQL or Apollo Studio).

Core Concepts

1. Schema Definition Language (SDL)

The SDL is used to define the GraphQL schema. Example of a simple schema:

graphql

# Define a custom type
type User {
  id: ID! # "!" means non-nullable (field must exist)
  name: String!
  email: String!
  posts: [Post] # Array of Post objects (nullable)
}

type Post {
  id: ID!
  title: String!
  content: String!
  author: User! # Relationship to User
}

# Define root operations
type Query {
  # Fetch a single user by ID
  getUser(id: ID!): User
  # Fetch all users
  getUsers: [User]
}

type Mutation {
  # Create a new post
  createPost(title: String!, content: String!, authorId: ID!): Post
}

2. Example Queries & Mutations

Fetch Specific Data (Query)

The client requests only the name and posts.title for a user with ID 1:

graphql

query GetUserWithPosts {
  getUser(id: "1") {
    name
    posts {
      title
    }
  }
}

Response: Only the requested fields are returned:

json

{
  "data": {
    "getUser": {
      "name": "Alice Smith",
      "posts": [
        { "title": "Introduction to GraphQL" },
        { "title": "Why GraphQL Beats REST" }
      ]
    }
  }
}

Create Data (Mutation)

A mutation to create a new post:

graphql

mutation CreateNewPost {
  createPost(
    title: "GraphQL Best Practices",
    content: "Use strong typing and avoid over-fetching!",
    authorId: "1"
  ) {
    id
    title
  }
}

Response: Returns the requested fields of the new post:

json

{
  "data": {
    "createPost": {
      "id": "101",
      "title": "GraphQL Best Practices"
    }
  }
}

How GraphQL Works (Simplified Flow)

  1. The client sends a GraphQL query/mutation to the single /graphql endpoint (via HTTP POST).
  2. The server validates the request against the schema (checks for valid fields/types/arguments).
  3. The server executes resolver functions (code that fetches/modifies data from databases/APIs) for each requested field.
  4. The server formats the resolver results into the exact structure requested by the client.
  5. The server returns the JSON response to the client.

GraphQL vs REST: Key Differences

AspectRESTGraphQL
EndpointsMultiple (per resource)Single (all operations)
Data FetchingFixed response structure (over/under-fetching)Client-defined response (exact data needed)
VersioningRequires API versioning (e.g., v1/v2)No versioning (evolve schema incrementally)
RequestsMultiple requests for related dataSingle request for all related data
TypingLoose (depends on documentation)Strict (schema-enforced typing)

Typical Application Scenarios

  1. Mobile Apps: Reduces bandwidth usage by fetching only necessary data (critical for low-bandwidth mobile networks).
  2. Complex Data Relationships: E.g., fetching a user, their posts, and comments on those posts in one request (avoids multiple REST calls).
  3. Microservices: Aggregates data from multiple microservices into a single GraphQL response (simplifies client logic).
  4. Real-Time Applications: Uses subscriptions for live updates (e.g., chat apps, real-time dashboards).

Popular Tools & Libraries

IDEs/Tools: GraphiQL (built-in playground), Apollo Studio, Postman (GraphQL support).

Server-Side: Apollo Server (Node.js), GraphQL Yoga, Graphene (Python), GraphQL Java.

Client-Side: Apollo Client, Relay (Facebook), urql.



了解 Ruigu Electronic 的更多信息

订阅后即可通过电子邮件收到最新文章。

Posted in

Leave a comment