GraphQL vs REST in PHP: What to Choose for API in 2024?

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction: REST or GraphQL — the eternal battle for speed and flexibility

\n

Hello, developer! If you've ever written an API in PHP, you've surely faced the dilemma: use the classic REST or the modern GraphQL. Both approaches solve the same problem — transferring data between client and server — but they do it in radically different ways.

\n

REST was the de facto standard for years: simple, clear, predictable. But with the growing complexity of frontends (React, Vue, mobile apps), developers increasingly complain about overfetching (too much data in the response) and underfetching (needing multiple requests to gather the required information). This is where GraphQL enters the scene — a query language that gives the client control over exactly which data to receive.

\n

In this article, we won't just list theory. We'll take real PHP projects (Laravel and Symfony), write code, and see what's faster and what's more convenient. Let's go!

\n\n

1. REST API in PHP: a classic that never dies

\n

How it works

\n

REST (Representational State Transfer) is an architectural style where each resource (user, article, comment) has its own URL. The client sends HTTP requests (GET, POST, PUT, DELETE), and the server returns a fixed data structure, usually in JSON.

\n

Example of a typical REST endpoint in PHP (without a framework):

\n
// index.php - simple REST API\nheader('Content-Type: application/json');\n\n$method = $_SERVER['REQUEST_METHOD'];\n$uri = $_SERVER['REQUEST_URI'];\n\nif ($method === 'GET' && $uri === '/api/users') {\n    $users = [\n        ['id' => 1, 'name' => 'Alexey', 'email' => 'alex@example.com'],\n        ['id' => 2, 'name' => 'Maria', 'email' => 'maria@example.com']\n    ];\n    echo json_encode($users);\n}\n
\n

In Laravel it looks even simpler:

\n
// routes/api.php\nRoute::get('/users', function () {\n    return User::all(); // Automatically serialized to JSON\n});\n
\n

Pros of REST

\n
    \n
  • Simplicity of caching: HTTP cache (ETag, Last-Modified) works out of the box.
  • \n
  • Ease of debugging: any browser or curl will show the response.
  • \n
  • Stability: REST has existed since 2000, documentation and tools (Postman, Swagger) are polished to perfection.
  • \n
\n

Cons of REST

\n
    \n
  • Overfetching: if the client only needs the user's name, it still gets email, phone, address.
  • \n
  • N+1 problem: to get a user and their posts, you need two requests (GET /users/1, GET /users/1/posts).
  • \n
\n\n

2. GraphQL in PHP: when the client is king

\n

How it works

\n

GraphQL is not a database, but a layer between the client and server. The client sends a POST request to a single endpoint (usually /graphql) with a request body describing which fields and relations are needed. The server returns exactly what was requested — not a byte more.

\n

Example implementation in PHP with the webonyx/graphql-php library:

\n
// schema.php\nuse GraphQL\\Type\\Definition\\ObjectType;\nuse GraphQL\\Type\\Definition\\Type;\n\n$userType = new ObjectType([\n    'name' => 'User',\n    'fields' => [\n        'id' => Type::int(),\n        'name' => Type::string(),\n        'email' => Type::string(),\n    ]\n]);\n\n$queryType = new ObjectType([\n    'name' => 'Query',\n    'fields' => [\n        'user' => [\n            'type' => $userType,\n            'args' => ['id' => Type::int()],\n            'resolve' => function ($root, $args) {\n                return findUserById($args['id']); // Your logic\n            }\n        ]\n    ]\n]);\n
\n

And now the client request:

\n
// Req                

Blogs

Book Recommendations