0Pricing
PHP Academy · Lesson

GraphQL vs REST

Understand when GraphQL beats REST and why.

GraphQL vs REST is a free PHP Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why GraphQL?

You already know how to ship REST APIs in PHP. GraphQL is not a replacement for HTTP or a magic bullet — it is a query language and type system that lets the client describe exactly what it needs and gets back exactly that, in one round trip.

In this lesson we contrast the two honestly: where GraphQL genuinely wins, where REST is still the right call, and what GraphQL costs you operationally.

Over-fetching and Under-fetching

The classic REST pain points:

  • Over-fetching: GET /users/1 returns 40 fields when the UI needs 3.
  • Under-fetching: to render a user's posts and each post's comment count you call /users/1, then /users/1/posts, then N comment endpoints.

GraphQL collapses this into a single declarative request.

query {
  user(id: 1) {
    name
    posts {
      title
      commentCount
    }
  }
}

One Endpoint, Typed Schema

REST exposes many URLs; GraphQL exposes one endpoint (usually POST /graphql) backed by a strongly typed schema. The schema is the contract — it is introspectable, so tooling (auto-completion, docs, code-gen) comes for free.

Below is a minimal schema in SDL. The shape of every possible response is known ahead of time.

type User {
  id: ID!
  name: String!
  posts: [Post!]!
}

type Post {
  id: ID!
  title: String!
  commentCount: Int!
}

type Query {
  user(id: ID!): User
}

The Response Mirrors the Query

A key property: the JSON response shape is predictable from the query. Clients never guess field names. This eliminates a whole class of versioning churn — you add fields without breaking old clients, and deprecate fields with @deprecated instead of cutting /v2 URLs.

{
  "data": {
    "user": {
      "name": "Ada",
      "posts": [
        { "title": "On Engines", "commentCount": 12 }
      ]
    }
  }
}

Where GraphQL Beats REST

GraphQL is the stronger choice when:

  • You serve many heterogeneous clients (web, iOS, Android) with different data needs.
  • The data is a graph with deep relationships clients traverse dynamically.
  • You want to aggregate multiple backends behind one typed gateway.
  • Rapid frontend iteration matters and you want to avoid endless backend endpoint changes.

Where REST Still Wins

Do not reach for GraphQL reflexively. REST is simpler and often better when:

  • You need HTTP caching — CDN/edge caches key off URLs and verbs; a single POST /graphql is opaque to them.
  • The API is resource-oriented and stable (CRUD over a few entities).
  • You rely on file uploads/downloads or streaming where multipart and byte ranges are first-class in REST.
  • Your consumers are third parties who expect conventional REST semantics.

A Quick PHP Comparison

Here is the same data assembled the REST way in PHP — notice the client would still need multiple calls or you hand-craft an embed param. GraphQL pushes that selection logic to the client instead.

<?php
// REST: server decides the payload shape
function userResource(int $id): array {
    return [
        'id' => $id,
        'name' => 'Ada',
        'email' => 'ada@example.com',   // over-fetched by mobile
        'createdAt' => '1815-12-10',
        'posts' => [                       // pre-embedded, all-or-nothing
            ['title' => 'On Engines', 'commentCount' => 12],
        ],
    ];
}

header('Content-Type: application/json');
echo json_encode(userResource(1), JSON_PRETTY_PRINT);

The Costs GraphQL Adds

GraphQL moves complexity to the server. New concerns you now own:

  • N+1 queries — nested resolvers fire one DB query per node unless you batch (DataLoader).
  • Query cost / depth limiting — a malicious deeply nested query can DoS you.
  • Caching is harder; you typically cache at the resolver/data layer, not HTTP.
  • Error handling differs — a 200 OK can still carry an errors array.

Errors: 200 With an errors Array

Unlike REST status codes, GraphQL conventionally returns HTTP 200 and reports partial failures inside the body. data can be partially populated while errors lists what failed. Your clients must inspect both.

{
  "data": { "user": null },
  "errors": [
    {
      "message": "User not found",
      "path": ["user"],
      "extensions": { "code": "NOT_FOUND" }
    }
  ]
}

Decision Heuristic

A pragmatic rule of thumb:

  • Public, cache-heavy, resource CRUD → REST.
  • Internal/product APIs feeding diverse rich clients over connected data → GraphQL.
  • Many backends to unify behind one typed contract → GraphQL gateway.

It is common and healthy to run both: REST for webhooks/uploads, GraphQL for the app's read graph.

Serving GraphQL Over HTTP in PHP

Operationally, a GraphQL endpoint in PHP is one route that reads the JSON body, pulls out query and variables, executes them against the schema, and returns { data, errors }. Compared to REST's many routes, the transport is uniform — all the variation lives in the query string the client sends.

<?php
// Minimal GraphQL-over-HTTP entry point
$input = json_decode(file_get_contents('php://input'), true) ?? [];
$query = $input['query'] ?? '';
$variables = $input['variables'] ?? null;

// $result = GraphQL::executeQuery($schema, $query, null, $ctx, $variables);
// header('Content-Type: application/json');
// echo json_encode($result->toArray());
var_dump(['query' => $query, 'variables' => $variables]);

Quick Check

When does REST keep a clear advantage over GraphQL?

Recap

You compared GraphQL and REST on substance:

  • GraphQL fixes over/under-fetching with one typed endpoint and client-driven selection.
  • It excels with many clients, graph-shaped data, and backend aggregation.
  • REST stays strong for cacheable public APIs, simple CRUD, uploads, and conventional consumers.
  • GraphQL shifts cost to the server: N+1, query-cost limits, caching, and 200-with-errors semantics.

Next: actually building a schema with webonyx/graphql-php.

Frequently asked questions

Is the “GraphQL vs REST” lesson free?

Yes — the full text of “GraphQL vs REST” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.

What will I learn in “GraphQL vs REST”?

Understand when GraphQL beats REST and why. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start PHP Academy?

No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “GraphQL vs REST” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this PHP Academy lesson?

Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. GraphQL vs REST
  2. Building a Schema with graphql-php
  3. Resolvers, Mutations and Subscriptions
  4. Performance: N+1 and DataLoader
← Back to PHP Academy