9 ms·
GraphQL vs. REST APIs: a complete guide
- revskill 4y agoJust like OOP vs FP. REST is OOP (you start with resource), Graphql deals with function (query and mutation).
- recursivedoubts 4y agoimma let u finish, but a hypermedia is a necessary constraint for an API to be RESTful... edit: more usefully, you need to be really careful w/ your GraphQL end points because they are being access in an untrusted computing environment: https://intercoolerjs.org/2016/02/17/api-churn-vs-security.html https://intercoolerjs.org/2016/02/17/api-churn-vs-security.h... my understanding is that facebook whitelists their graphql queries but, last I looked, I didn't see security getting much attention around it...
- denysonique 4y agoFor JavaScript based projects TeleFunc[1] can make development way simpler by 'removing' the need for an API. [1]: https://telefunc.com/ https://telefunc.com/
- diceduckmonk 4y ago> For JavaScript based projects This is viable for personal projects and things that exist in a vacuum. Suppose you hit a performance bottleneck with your backend and want to migrate to Go Or, if you want talk to your JavaScript background from a native mobile client. Or if another team or customer wants access to the API and not using JavaScript. gRPC solved this problem by having Protobuf as the many-to-many translation layer. Client stubs and backend service stubs in a variety of languages are autogenerated. Telefunc is a subset of this wherein you define the Interface in TypeScript instead of protobuf. With gRPC you also get a binary encoding over the wire. Maybe the effort of the project could have been building on top of gRPC (which is not necessarily coupled to protobuf) and adding automatic codegen tooling for JavaScript.
- coolgoose 4y agoWell, seems somebody doesn't care about jsonapi/openapi and the rest of the family. Sparse field sets / compound documents are nothing new and I'd argue its easy to overlook that there's no magic in the backend for graphql either.
- zoover2020 4y agoI think OP didn't make the distinction between RESt and RESTful APIs. A pity IG you'd ask me
- jensneuse 4y agoHere's how you do it: - REST/Hypermedia when you're actually building a website (not app) and your "site" is a state machine - OpenAPI when you expose and API to 3rd parties - Isomorphic TypeScript APIs when you're using TS on both backend and frontend [0] - GraphQL when the frontend needs to talk to an API layer provided by different teams - OpenAPI when one backend talks to another backend - gRPC might be an option, but most teams don't need it [0]: https://wundergraph.com/blog/isomorphic_typescript_apis_end_to_end_type_safety_between_client_and_server https://wundergraph.com/blog/isomorphic_typescript_apis_end_...
- deleted 4y ago[deleted]
- flashgordon 4y agoOne thing Id suggest - "gRPC might be an option but most teams dont need it" - needs a revisit. As a backend-dev (who does front end when needed - and that too by slapping NextJS on an API) I have found starting from a grpc set of services and generating http/openapi specs from it to be much for maintainable and understandable than starting with the OpenAPI spec and working "inwards". Apart from a (mostly) single source of truth for my interface intent - I also get a system that is amenable to scalability concerns than most of the time when I started working inwards. I might be in the minority as most folks who build services come from a product background?
- jensneuse 4y agoIf we compare gRPC to OpenAPI, we get the following. gRPC will be faster at the tradeoff of complexity. You need more tooling, you cannot easily inspect binary traffic, you cannot simply call gRPC from the web, you need a grpc web proxy, proxies and API gateways are more complex for gRPC than for an OpenAPI/REST-ish API, and the list goes on. I can put my protobuf in a registry, but the same applies to OpenAPI. So what really is the difference? And do we really need the gRPC level of performance with this hefty price of complexity? I doubt it. Most of the time, your database will be much slower than what gRPC might give you in performance compared to OpenAPI. Sorry if I'm pushing back on this. It's not against you. I've just seen way too many devs and teams who created gRPC "micro" services and all they needed was one boring well designed OpenAPI monolith with good architecture. gRPC is great if you really really have the problems it tries to solve. I believe most companies have a much bigger problem than performance, the inability to design APIs. You cannot solve bad API design by using a faster tool. Fix your API design, OpenAPI is great.
- deleted 4y ago[deleted]
- satvikpendem 4y agoGraphQL is extremely useful, if only to have strong type validation between disparate languages, via code generation. It can be a universal typed schema of your data against which you can use whatever server and client combo you want. It's like tRPC but you're not forced to use only TypeScript. I also have to plug this video [0], since many people think GraphQL somehow is a competitor to SQL and that it goes between the server and the database; it does not and has not ever been intended to be a replacement for a database query language and in fact should never be used there at all. It is only for client/server communication, not server/database communication. [0] https://www.youtube.com/watch?v=ZfccwYUD8H0 https://www.youtube.com/watch?v=ZfccwYUD8H0
- yencabulator 4y ago> strong type validation The limited types in GraphQL kinda make that not very helpful. A RESTful API with JSON Schema or zod schema for it has much stronger types, and you can even make converting to better types be part of the zod schema.
- satvikpendem 4y ago> A RESTful API with JSON Schema Sure but I get it for free with GraphQL anyway. > you can even make converting to better types be part of the zod schema I'm not using TypeScript so this wouldn't be useful to me. That's why I mentioned that GraphQL is good for disparate servers and clients that aren't necessarily just React/Node/TypeScript.
- deleted 4y ago[deleted]
- hbrn 4y agoI really hate these bland, barely actionable advices with no examples, created for SEO purposes. Nobody knows how to measure the "complexity" and "evolvability" of the API and where exactly is the threshold that justifies going from REST to GraphQL. So here's my opinionated alternative: Use REST everywhere, unless you can justify the exception. A good exception is when you don't know the audience and use cases for your API. E.g. if you have hundreds of different apps using the same API and you have no idea how they are going to use it. You know who does it? Facebook. If you're just dogfooding an API for your website, you don't need GraphQL. If you need one service to talk to another, you don't need GraphQL.
- diceduckmonk 4y ago> created for SEO purposes I’ve always thought these posts were for non-technical product buyers and decision makers.
- braindead_in 4y agoREST is basically a subset of GraphQL.
- eterps 4y agoFrom a caching perspective REST is a superset IMHO.
- TurningCanadian 4y agoThere's a lot to caching that REST gets wrong. It thinks in terms of URLs being cacheable, but that's very limiting. GraphQL caches at the level of the objects in the response. Almost every REST API will return multiple objects from one URL. With GraphQL, newer data coming in from query2 can update components showing data from query1 if they both reference the same object even if query2 is a different URL. REST just doesn't have those smarts. Yes, a HTTP DELETE request will clear the cache for a particular URL, and there's no equivalent in GraphQL, (that I know of) but I don't think I've ever been able to take advantage of that in real life. At the network level, GraphQL can automatically set cache headers depending on the content. REST doesn't know what you're sending, so it's up to you to know that when you start sending mixed data (to save clients a roundtrip), the cache header may be impacted. https://www.apollographql.com/docs/apollo-server/performance/caching/ https://www.apollographql.com/docs/apollo-server/performance... On the client-side, caching with GraphQL is far ahead of dealing with a REST API. It knows more about what data it has in cache so it's better able to automatically avoid network requests. Further, a cache-and-network fetch policy is just another parameter for your query and the plumbing for that is handled transparently.
- twodave 4y agoI like GraphQL because it allows me to describe my API like a domain rather than just a collection of resources. REST is difficult to map to a true domain model because domains aren't just collections of resources. They have nuance. And with GraphQL your API matches your domain, so there's no limit to what your application can accomplish. For example, adding another feature to your front-end no longer requires going back to your API to add a tailored endpoint nearly as often. At worst you're adding a property somewhere that is now available to all your use cases. GraphQL embraces mutations in a way that REST frankly can't without being glorified RPC, and it doesn't have the same perverse incentives such as re-using an endpoint because it exists even though it may be suboptimal. So, in my opinion, unless your application is very resource/entity-intensive (and you don't mind a little RPC-style bloat) then GraphQL is often a better choice than REST. And if you actually have a rich domain to model (this is the case even for many small applications), then GraphQL is often a better choice than RPC.
- gofreddygo 4y agoI love graphql. It allowed me to scrape a whole bunch of websites with almost no changes to my scraper.
- berkle4455 4y agographql is a data exfiltration engine, it's lovely
- twodave 4y agoHow is this different than a REST API with an open api spec? I suppose GraphQL APIs are just more likely to have introspection turned on since it’s the default?
- gofreddygo 4y ago> with almost no changes to my scraper Thats the killer feature.
- marcosdumay 4y ago
- ElijahLynn 4y agoArticle could be improved by mentioning that the smaller rest requests will have a much higher cache hit ratio when used with HTTP/2.
- brasic 4y agoEverything is higher than zero. GraphQL is inherently not meant to be cached at the transport layer which is why it’s often exposed behind HTTP POST. If caching GraphQL makes sense for your application you probably didn’t need GraphQL in the first place.
- WirelessGigabit 4y agoI don't like that GraphQL is called GraphQL. Its output cannot represent a graph. Its output is finite. Consider an API that queries people. You query a married person and include their spouse. And then you include the spouse's spouse, and so on. GraphQL will render as many levels as you request without deduplication. JSONAPI will do this much better, you'll get 2 entities in 'data', and they'll refer to each other in their relationships block. Not that I like JSONAPI. Having built larger system with it there is no universal way of supporting pagination in the includes section which makes it a binary proposition about includes. You get ALL the ones you request, or none.
- foota 4y agoIt's a query language for graphs, not a language for transferring graph data.
- chrsjxn 4y agoThe article talks about how GraphQL is "flexible" a lot, but I kind of wish they'd spend more words talking about why that matters. Eg, if you're working on a new product, the odds are very good that your front ends will change pretty rapidly. At the very least, we're way more likely to A/B test application features than we are API schemas, regardless of what methodology or technology our APIs are using. Because that's why I would pick GraphQL. It's a choice that reduces the barrier to rapid iteration in the clients, but it does add backend and infra work to support it.
- diceduckmonk 4y ago> "flexible" a lot, but I kind of wish they'd spend more words talking about why that matters. I don’t think these articles exist for a technical audience or the bricklayers doing the integration. I think these are for the non-technical decision makers and business executives
- blagie 4y agoI don't like GraphQL due to the complexity. It's not JSON or YAML, and requires a lot of custom stuff on both ends. I'd like something like GraphQL, but built on standard data formats.
- mb7733 4y agoEvery graphql API I've ever seen returns JSON. It's definitely the standard. What are you referring to?
- habitue 4y agoI think they're referring to the query language itself not being json or yaml
- blagie 4y agoExactly. It's not just not-JSON, but it's obnoxious and hard to manipulate programmatically, on either end (client or server). That translates to a lack of tooling around it, an inability to write sane tooling, and difficulty interfacing in higher-order ways to things like interesting data stores. It's designed to be hand-written and parsed only with the official libraries.
- yencabulator 4y agoIt hasn't seen much outside adoption, you might enjoy the ideas behind Netflix's Falcor: https://netflix.github.io/falcor/ https://netflix.github.io/falcor/ You can think of it as larger-than-what's-downloaded dynamically-generated JSON object with internal pointers where you can ask to access wanted paths. (Sort of like GraphQL is a larger-than-what's-downloaded dynamically-generated non-JSON object.) One trick they use is that the path segments can also be objects, so `{from: 100, to: 200}` is a valid path segment, and this is how you build fancier query logic with in. https://youtu.be/hOE6nVVr14c?t=977 https://youtu.be/hOE6nVVr14c?t=977
- gtramont 4y agoI take not mentioning hypermedia in a post discussing REST as a huge red flag. The author mentions Roy Fielding's dissertation, but apparenly they didn't read it thoroughly. Furthermore, I believe that a huge confusion comes from not understanding what a "resource" is: it is not a database table*; it is not your domain model*; it is a _representation of state_. Like this very orange page you're looking at. This whole page is the resource identified by https://news.ycombinator.com/item?id=35014395 https://news.ycombinator.com/item?id=35014395. Just like the stylesheet for this website is a resource identified by https://news.ycombinator.com/news.css https://news.ycombinator.com/news.css. * It may be, if that's the _representation_ you want.
- ynab4 4y ago[dead]
- JanisErdmanis 4y agoThe naming of "resource" is a bit unsettling. From the perspective of the server, it seems natural to think of all databases and external machines. "Representation" sits better with me, but ultimately in the code, I would prefer to name the REST endpoint as a "service".
- nonethewiser 4y agoREST is such a bastardized term. At this point it’s often used synonymously with JSON/HTTP or simply meant to contrast between SOAP, GQL, gRPC, etc. without respect to its actual tenants.
- IceDane 4y agoThere seem to be a lot of people pushing back on GraphQL who often don't seem to understand what it really is, or what it can do. They often seem to think that it's super complicated to build and use, and that REST(-ish) APIs are somehow magically simpler and easier. Are RESTish APIs simple to build? I mean, yeah. You can have a server running serving an endpoint in like a minute in most programming languages. But FWIW, this also applies to GQL. Take a gander at any GQL resolver tutorial. But is that really what makes it simple? When you build APIs, they aren't made to exist in isolation. They're made to be consumed. Ideally, they should be easy to consume, which can mean a lot of things.. but "it's easy to send an HTTP request" is not one of those things. They're easy to consume if they are documented and come with schemas. They are easy to consume if there is tooling to generate fully typed clients for them. Arguably, OpenAPI schemas could fit this description, but in my experience, OAPI support is really varied, both on the server and for clients. Generated clients tend to be lots of code and incredibly clunky. Support server-side is heavily reliant on the server libraries being capable of exposing schemas in some way. In some languages this is trivial, but in e.g. javascript or typescript, you will need some way to expose your types. Just having typescript interfaces isn't enough(without extra tooling or reflection). GraphQL is typed by definition. The schema is the API, and the types, and the documentation. We have great tooling to generate code in any language, and code-first resolver libraries(like the excellent pothos-graphql.dev) make building your schema along with your resolvers an absolute joy. Then there's things like the N+1 problem. RESTish APIs are sort of "procedural". Each endpoint is usually a resource, and if you want to fetch a resource and its related resources, you will often have to fetch it and them separately. You can also embed them in the resource, or you can resort to all sorts of not-very-standardized methods of conditionally expanding relationships to do it, which is already just sort of doing what GQL does, except much worse(and is I think not supported in OpenAPI at all?). In GQL, you can also run into N+1, but modern libraries make this super easy to solve. Either they can tightly integrate with something like the underlying ORM, or you can write dataloaders for your types, so that every time a specific resource is requested en-masse, it is always loaded efficiently. Not so much for REST, unless you apply very careful engineering and design. GraphQL just makes all these things such a breeze. There are some things you need to think about, of course. Query complexity is one thing; you don't want someone to bring down your server using 30-level nested query. Thankfully, people have been using GQL for years at this point and most of these problems are solved, and many of them incredibly neatly.
- doctoboggan 4y agoI've been writing flask apps for a while (using sqlalchemy as my ORM) and find myself repeating code all the time when I create GET and POST end points for all my models. Is there a better, more automatic way to generate GET and POST endpoints automatically when I create a new model?
- nonethewiser 4y agoThe anti GQL circle jerk goes too far. GraphQL is often overkill but it’s awesome if you take advantage of the powers of federation and field specification. If you don’t see a difference between retrieving all fields and just the ones you need then you just haven’t encountered the cases where it makes a difference.
- ishjoh 4y agoI have used GraphQL and REST extensively. I prefer REST. It is easier to cache server side which for certain types of data can be extremely useful. It works well with monitoring software. It is extremely easy to understand with just using curl. Graphql works extremely well with React. The Graphql Apollo React client fits like a glove and is a pleasure to work with. I have not found a REST library that fits as well although there are likely some now.
- beders 4y agoNowhere near a complete guide or even balanced comparison > GraphQL is a highly flexible option that’s better suited for building APIs that require complex data fetching and manipulation. It deftly avoids over-fetching and under-fetching data, leading to lower bandwidth usage and faster response times. Yes, but have you tried implementing one? It is not trivial at all to write performance GraphQL backends. Often, it's a n+1 query you didn't write a batching version for that messes you up.
- mostertoaster 4y agoThe main issue that happens with both REST and GraphQL, is that people spend more time thinking of how to implement their thing, than what the API should be. The complexity GraphQL adds _can_ be worth it for its ability to better represent a business domain via an API. If you don’t care how well your API represents your business domain, then likely your API is going to suck, and you might as well have a sucky REST api and avoid the complexities of GQL.
- b212 4y agoI had the pleasure of working with Apollo + GraphQL for the last 2 years and I don’t understand the hype. I haven’t seen anything so over engineered and complex in my whole 20 year long career. To make things worse I quickly found out all the problems GraphQL tries to solve are still there. Like over-fetching is around the corner if you don’t pay attention. REST on the other hand feels really straightforward, maybe easier to mess up but also much easier to fix. I’d take Redux over Apollo anytime even though Redux is dying according to many.