What is GraphQL, and how does it compare to REST?
Quick Answer
GraphQL is a query language for APIs: one endpoint, and the client specifies exactly which fields (across related types) it wants in a single request — solving REST's over-fetching and under-fetching. Trade-offs: HTTP caching is harder, you need query-complexity limits and a DataLoader to avoid N+1, and the server is more complex.
GraphQL gives the client one endpoint and lets it ask for exactly the fields it needs, including across related objects, in a single query. That kills the two REST annoyances — getting back more than you wanted, or having to make three calls to assemble a screen. The downsides are that it's all POSTs to one URL so HTTP caching doesn't just work, you have to add query complexity limits so someone can't send a pathological deep query, and the resolver model causes N+1 unless you use a DataLoader to batch. For a rich client aggregating several backends it's great; for a plain CRUD service REST is simpler.
- Strengths: the client shapes the response; one round trip for a nested graph; strong typed schema and introspection; great for aggregating many backends for varied clients.
- Weaknesses: everything is a
POSTto one URL, so CDN/HTTP caching doesn't work out of the box; a malicious deep query can hammer the DB (need depth/complexity limits, persisted queries); resolvers naturally cause N+1 — use a batching DataLoader. - .NET: Hot Chocolate is the mature server.
- Not a REST replacement everywhere — a simple CRUD service is fine as REST.