19 ms·
REST vs. GraphQL – A search for evidence on which is better
- rhacker 6y agoYes, had this discussion on here before. While in REST you can more or less optimize a service to be performant at what it does, the moment there is another service that you need to fetch some additional data, the browser would be required to orchestrate that, which means you're also waiting for the return trip on the first call before you can even get the secondary data. This alone makes REST far less favorable in my opinion. The secondary is that operations are standardized in GQL. Whereas in REST I can pass data in through: Query params Body Headers Path variables Each team will do this differently. In graphQL these inputs are pretty much standardized and you have the option to implement security through headers. This makes GQL decoupl-able from HTTP (at some point). That's a great incentive too by itself since at some point the web may just be media distributions + services. Where media distributions is just HTML/CSS/JS/etc... There's new reasons as time moves forward media distributions needs to take place over HTTP. The top response to this is caching - in other words every device on the planet knows HTTP so caching in GQL becomes a secondary thought. So yeah there's that. GQL has some variously applied caching semantics - so YMMV but personally I still feel like the gains from the first point are so dramatic that most people won't really care about this.
- ehutch79 6y agoYou do realize there's no reason a rest endpoint can't support doing this. My endpoints take a 'fields' parameter... and those fields can themselves be serialized objects.
- jiofih 6y agoVery lazy thinking. It doesn’t have types, do introspection, batching, granular caching, access control... I suggest reading the GraphQL introduction post for a start: https://engineering.fb.com/2015/09/14/core-data/graphql-a-data-query-language/ https://engineering.fb.com/2015/09/14/core-data/graphql-a-da...
- verdverm 6y agoThese things have overhead and access control is more difficult to reason about and implement with resolvers and nested query resolving.
- jiofih 6y agoThat may be true, but has no bearing on the fact that being able to add a “fields” param is not by any measure an alternative to what GraphQL provides.
- atom_arranger 6y agoThe problem with this is the “my endpoint” part. This functionality is automatically part of every GraphQL API, and it is consistent. The same issue applies to types and documentation, you can do it with REST, but it’s inconsistently done.
- the_arun 6y agoRegarding decoupling GraphQL from HTTP - do we need this? cause are there plans to use GraphQL on different protocols like raw TCP? Isn't GRPC better for raw TCP? When we are using HTTP, diluting HTTP standards - eg. using POST for both creating & updating, returning HTTP 200 for errors seem to be hacky in GraphQL. I always found REST to be more simple & straight forward. With progression in HTTP itself - HTTP/2, HTTP/3 etc., chatty behavior of REST may not be expensive. Implementing roles & permissions in GraphQL tricky. We need clear schema definitions to control it. Huge learning curve as well.
- GordonS 6y agoFrameworks like WCF (Windows Communication Foundation) used to support different transport level protocols, like TCP, but IMO that discussion is long over, with HTTP the obvious winner. And of course, the overhead is even less these days with HTTP/2. I find GraphQL not being coupled to HTTP to be a problem, no a benefit - as you say, returning HTTP 200 for everything is just daft.
- enobrev 6y agoYou're not wrong, and to resolve this, I've implemented something of an in-between for APIs I work on, which I call a "Multi-Endpoint Query". It's a restful(-ish) API, but there's an additional endpoint called "query", which allows for an array of endpoints to gather information from sequentially. The most useful bit of this is that information gathered from earlier in the array can be used as referenced later in the array. For instance: "query": [ "/api/category/books/products", "/api/products/{products.id}/images", "/api/products/{products.id}/reviews", "/api/users/{reviews.user_id}" ] When the endpoint gets this query, it will run a GET on the first endpoint. And then it uses the results from that first endpoint to fill in the uri template on the 2nd endpoint, which would become something like "/api/products/2,4,17/images". And the results of all previous endpoints are merged into the response and can be used to fill subsequent uri templates as well. As far as the client is concerned this is all done in a single API request. The first version was making literal HTTP requests to localhost, but now is built to call the endpoints directly (internally, no HTTP). This system requires some convention in the responses to make it work, but that convention ends up making responses predictable and easily reusable. Overall it's worked very well and requires almost no additional effort. I have a similar endpoint that also allows "POST"s which makes for seriously complex single-request interactions, but I don't use that as much due to the inherent complexity of it - at least not for client-side APIs. When I first looked into GQL, it looked pretty fancy, but seemed to require quite a bit more maintenance to define the query space. This was before a lot of today's libraries were available. So I hacked together the Multi-Endpoint Query, assuming if it failed, I could go back to GQL when there were more libraries available. But I haven't really needed to do so since.
- coding123 6y agoAnd there's nothing wrong with that. You essentially invented your own GQL because it contained some awesome ideas. Also I think it would be OK if new things similar to GQL came out and challenged it. I don't think GQL is perfect, and I personally wish it had namespacing and more thought about caching built in.
- mssundaram 6y agoGiven your example request, what would be the schema of the response?
- treis 6y agoThere's no law against putting joined data into a REST endpoint. As an example, I had to consume an API for a customer's subscriptions. They did it by the book where Customer has Subscriptions which has Items which has Prices. That was a huge performance issue for us because it was 4 round trips. But they didn't need to use GraphQL. They just needed a fullDetails end point for subscriptions.
- cratermoon 6y agoIn DDD this is the Aggregate pattern. https://martinfowler.com/bliki/DDD_Aggregate.html https://martinfowler.com/bliki/DDD_Aggregate.html Essentially, a graph of objects that must be treated as a single entity. I've seen quite a few REST implementations that have separate calls for the root and branches, like Order and LineItems. In the Aggregate pattern, you treat them as an entity that travels and transacts as one.
- tingletech 6y agooriginal link https://arxiv.org/abs/2003.04761 https://arxiv.org/abs/2003.04761
- remram 6y agoThank you! All I saw at the original link is a list of papers (with endless scrolling), and I wasn't sure what the discussion was about...
- Lapsa 6y agoyou must construct additional ~pylons~ abstraction layers
- cratermoon 6y agoInteresting thought because I see GraphQL as removing a layer of abstraction. Instead of modelling the domain activities and abstracting away the storage model, GraphQL can end up just being a way to express a relational model and SQL as JSON. Except it's not as featureful or complete as the real relational system.
- yumraj 6y agoAre there any performance benchmarks comparing REST and GraphQL?
- wobblyasp 6y agoThey'll both be as fast as your implementation; but GraphQL will most likely have some additional overhead, likely offset with caching. GraphQL isn't a magic bullet; you still need to implement/define how the data is returned.
- IshKebab 6y agoI think they're too different for that to be meaningful. GraphQL lets you do way more in a query, which means you need fewer queries. It would be like comparing PostgreSQL with Redis, or something.
- yumraj 6y agoYes, GraphQL would require fewer round trips than corresponding individual queries via REST, but that logic of mapping a GraphQL query to individual SQL queries from the DB resides in the GraphQL layer. So, the question is how does that overhead compare to the overhead caused by multiple REST api calls? And, in addition, how do the GraphQL layers scale as the GraphQL queries become complicated and larger.
- dimitrios1 6y agoAdmittedly I skimmed -- observed that the paper dove really deep into time to perform queries and implement desired behavior, but didn't spend much time on implementation of GraphQL vs a REST API. One statement made that stood out to me: > it is clear that the availability of a type system—expressed as a schema— is one of the key benefits provided by GraphQL So I wonder what the results would look like if you had an OAS spec file for the API you were hitting (with autocomplete in VSCode), seems to me that's the best of both worlds: ease of implementation on the server side, ease of use on the client side. This to me feels like an argument of better tooling and (self) documentation rather than one technique over another.
- emilecantin 6y agoAs someone who's worked with both approaches, at all levels of the stack (both backend and frontend), I think the paper (at least, its abstract) is missing the point. While I do "feel" faster when working with GraphQL, I think the main benefit is that it abstracts away the busywork of transferring data between frontend and backend. Writing a backend becomes more about describing what data is available, on what terms, how it fits together, and the operations you can do on it (mutations). Gone is the busywork of writing routes, handling CRUD in a zillion slightly different ways, etc. On the frontend, Apollo-client lets me just write my app, not having to handle data-fetching, loading & caching for the zillionth time. I need an additional field? Just add it to the query! No need to get everyone involved. Of course, there are traps you can easily fall into with Apollo's caching, N+1 queries on the backend, etc. But in my experience, while you do have to "drop down a level" sometimes to fix these, you spend most of your time at the "higher level".
- zanellato19 6y agoI have the opposite experience working on the backend. GraphQL is too prone to N+1s and other inefficiencies because its in direct opposition of the way data is stored. Its much harder to make an efficient resolver than it is making an efficient REST endpoint. Errors are harder, because HTTP codes are not used and monitoring is a lot more complicated. I see value in GraphQL - but I think it brings a lot of cost to the table.
- gabereiser 6y agoCan you give some concrete examples on the N+1 problem? I’ve heard this before but never experienced it.
- dudul 6y agoa query that lets you fetch a list of posts, each post has an author field. So if you ask for these, a naive backend will "resolve" the author for each post individually (so N queries to the DB to fetch 1 author each time) as opposed to a single resolution for the batch of authors.
- ehutch79 6y agoAm I missing something, or was this only about implementing queries with a fixed backend? What's the numbers on implementing these? In different languages other than javascript? Last time I looked, implementing graphQL with django was pretty janky and limited.
- sandstrom 6y agoI read this article about GraphQL vs REST a while ago, and found it quite interesting. https://www.graphiti.dev/guides/why https://www.graphiti.dev/guides/why The author is arguing that by borrowing a few ideas from GraphQL, a “modern” REST API gets the benefits of both.
- recursivedoubts 6y agoThe results are intuitive and in favor of GraphQL, especially as query complexity increases. GraphQL makes loads of sense for modern javascript thick clients: The front end developer is going to want the same thing that a back end developer has: an expressive, general query language. And the API developer should want to give it to them so they aren't dragging their API around all over the place as fiddly UI & application logic changes are made[1]. I'm glad to see javascript client-server apps heading this direction, and leaving REST/HATEOAS to hypertext-oriented approaches[2]. REST sans a hypertext was always a mistake. [1] - https://www.infoq.com/articles/no-more-mvc-frameworks/ https://www.infoq.com/articles/no-more-mvc-frameworks/ [2] - https://htmx.org https://htmx.org
- djlewald 6y agoI am a fan of GraphQL, but what evidence do you have for "REST sans a hypertext was always a mistake"?
- recursivedoubts 6y agoREST requires a uniform interface. Hypertext (or media) is that uniform interface. JSON isn't a hypertext. Therefore JSON isn't an appropriate transport for a REST-ful API. I understand that 99% of the internet disagrees with me.
- t-writescode 6y agoCould you define your terms? Especially: * uniform interface * hypertext And even more especially how JSON does not meet the requirements?
- recursivedoubts 6y agoUniform interface: https://en.wikipedia.org/wiki/Representational_state_transfer#Uniform_interface https://en.wikipedia.org/wiki/Representational_state_transfe... Hypertext: https://en.wikipedia.org/wiki/Hypertext https://en.wikipedia.org/wiki/Hypertext JSON is obviously not a native hypertext, any more than plain text or CSV is. You can, of course, embed URLs in it (or any other format) and call it a hypertext. That's usually pointless, as the links will be consumed by code (rather than a human, in the canonical HTML->browser interaction) so if the URLs aren't simply ignored, they will be dealt with generically. I wrote about this in HATEOAS is for humans: https://intercoolerjs.org/2016/05/08/hatoeas-is-for-humans.html https://intercoolerjs.org/2016/05/08/hatoeas-is-for-humans.h...
- zwily 6y agoI think this paper misses the point. If you're a front-end developer, if you have a robust graphql endpoint available to you it's unbelievably amazing and productive. But providing a robust graphql endpoint that is performant, scalable, secure, etc, is much more difficult than REST. GraphQL is optimizing for a different set of developers, and this paper only studied one group.
- Marinlemaignan 6y agoAgreed with this, you definitely don't want to be the one implementing it on the backend it is no fun at all and can be quite tricky with all the n+1 you didnt see coming and all that.
- valenterry 6y agoThe n+1 would be there with REST too. Unless you have specific, optimized REST routes - but then you can do the same with specific, optimized graphQL queries too.
- anamexis 6y agoWell, I would argue with "true" REST, all of your REST routes are specific, and generally therefore easy to optimize.
- valenterry 6y agoWhy would your routes with REST magically be specific and your queries with GraphQL not?
- dyeje 6y agoREST endpoints typically return a specific set of data that you can optimize queries for. Whereas the GraphQL endpoint must handle arbitrary queries which will require some logic to prevent N+1 queries on the related tables or even resolve to other data sources.
- srameshc 6y agoRead a lot about how Relay is better than GraphQL Apollo client, but haven't got much info on the adoption of Relay vs Apollo client and Relay is too complicated. Now this has added to more GraphQL vs Rest complexity.
- treve 6y agoThis paper has a pretty naive understanding of REST. While 'REST' can mean something different depending on who you talk to, I think in the context of a paper we can expect a bit more research. This paper takes a typical query, and just overlays it on a CRUD-style REST endpoint, but it ignores: * REST can definitely be strongly typed. There's OpenAPI, and JSON-Schema. In many instances I think this will work better than GraphQL, as the data you get back is more likely to follow a fixed format. * Mutations. In GraphQL this is an RPC-style feature, whereas with the typical 'REST as CRUD' API you write in the same format you read, which can make this a lot simpler. * Discovery. The paper discusses that REST can benefit from an 'IDE', but if you do REST well your browser is your IDE and you serve text/html as well as JSON. Ignoring good hypermedia APIs that serve multiple formats, there's also systems that let you test APIs based on for example OpenAPI schemas. To me this is not a comparison between REST and GraphQL, but a comparison between GraphQL and a GET request on a poorly documented, low effort HTTP endpoint. To be fair, many APIs are just that.
- zachrip 6y agoI think REST is definitely playing catch up here though. A standard gql setup generally comes out of the box with type generation, web playgrounds, etc. Of course it's possible now with REST but I really think that gql helped push the state of the art in this space.
- murukesh_s 6y agohuh! Swagger playground is there at least one year before[1] gql was used internally in Facebook and several years before it was available publicly.. [1] https://en.wikipedia.org/wiki/Swagger_(software) https://en.wikipedia.org/wiki/Swagger_(software) [2] https://en.wikipedia.org/wiki/GraphQL https://en.wikipedia.org/wiki/GraphQL
- boublepop 6y agoWe’ve had these aspects out of the box with oData REST endpoints that have been in production for half a decade.
- draw_down 6y agoAfter lots of experience with REST, and some months of graphql, I'm having a hard time arguing for the latter.
- steverb 6y agoI'll be honest. I hate GraphQL. It probably makes sense in a world where everyone uses graphQL, but to me it felt like having to learn yet another query language to do what to me seems straightforward using a simple REST api. I may also be old and cranky and you should probably get off of my lawn.
- fatbird 6y agoI'm with you. I've done big REST APIs and now have a big GraphQL API on my ongoing project, and I wouldn't do GraphQL again for anything I'm working on. The beneficial use cases for GraphQL are far narrower than presented, and the extra overhead compared to REST isn't worth it.
- mumblemumble 6y agoMy sense is that GraphQL makes the impossible stuff hard and the easy stuff hard. So its relative merits have a lot to do with how complicated a thing you're trying to do in the first place.
- jensneuse 6y agoWhat would you say are the hard things about GraphQL?
- mumblemumble 6y agoKeeping database load under control, for example. With an API that keeps tighter control over access patterns, you've got a more predictable target for optimizing your indexing strategy. With GraphQL, you've got to worry about the possibility that some client figures out how to craft a query that slips between all your indexes and causes the database engine to resort to doing things the hard way. So, worrying about that stuff is hard, where it tends to be easier to manage with REST or gRPC because you can just force your worldview onto consumers and get on with your life. In theory, though, a well-crafted GraphQL API can be more performant over a wider variety of use cases than a well-crafted REST API, for all the oft-cited reasons. So it does make the impossible possible. But not (necessarily) easy.
- jsjohns2 6y agoThis is a flawed comparison. GraphQL is probably a superior query language. The more salient question is how the complexity of back-end API endpoint implementation differs. The answer is that it varies widely between ecosystems (i.e. you are going to have a totally different experience developing a GraphQL endpoint in PostGraphile, Graphene, and Apollo)...and the paper doesn't mention which back-end technology was used.
- jasonhero 6y agoAs someone who has heavily used both REST and GraphQL in the past and actively, I find this comparison heavily similar to using raw HTML versus React. When it really boils down, GraphQL is just REST with types and the capability of performing multiple requests in one. Much like React is a way of creating component types from HTML elements. GraphQL takes a bit more work to get setup and running, but it's soo worth it in the end if you value typing. One of the most impressive parts of GQL that REST isn't capable of having, is the vast tooling ecosystem enabled by a standardly typed data transfer model, the fact that anyone can write a library that can automatically hook into your model is incredibly powerful. I find most people who have negative opinions on GraphQL simply haven't taken the dive yet to fully understand it, and they typically overthink what it actually does. In my opinion, if you're writing a progressive web/mobile app with relational data, you should hands down be using GraphQL.
- say_it_as_it_is 6y agoWhat are the tradeoffs for doing so and what makes them more compelling? What applications don't benefit as much by using GraphQL?
- intellix 6y agowell it's literally just a tree of functions with extra metadata to make it extra powerful. Also have used both REST and GQL heavily and it essentially solves lots of problems I had with REST. I'm never writing REST again and when I see that something I'm consuming also have a GQL API it makes me so happy to be able to know every single field available to me. The only use-case where it's annoying me is a CMS for building an entire site. It's recursive as A -> B -> A -> B and the lack of recursion as of yet makes it manual work to extract every level that you need.
- gsvclass 6y agoThe site 42papers.com that serving this link is build with Super Graph a GraphQL to SQL compiler. Tech like this makes GraphQL clearly the easier, faster and better option. I built Super Graph since I wanted something better than REST while building apps and did not want to go down the rabbit hole of GraphQL frameworks where I would still need to write and maintain all the database query code for the app. I started out not liking GraphQL cause it didn't really reduce the code I needed to write but on digging deeper it seemed to be the best way to represent a data query from an app now only if something could convert that into SQL automagically. This was the motivation for Super Graph. https://github.com/dosco/super-graph https://github.com/dosco/super-graph
- deleted 6y ago[deleted]
- cratermoon 6y agoI just looked at Categories list there at https://42papers.com/categories https://42papers.com/categories and WOW is it broken. Examples: Social and Information Networks category description is: Covers all aspects of computing with sound, and sound as an information channel. Includes models of sound But over in Audio and Speech Processing the description says: General methodological and applied contributions to economics.
- gsvclass 6y agoThe categories are from ARXIV this is how they have defined stuff. I'm working on adding our own tag layer on top. https://arxiv.org/category_taxonomy https://arxiv.org/category_taxonomy
- cratermoon 6y agoWhatever you're using to transform the arxiv taxonomy, it's wildly mixing up the category names and descriptions.
- say_it_as_it_is 6y agoDoes this actually pass as an academic study? It is presented in the format of a study (it looks like one) but to suggest GraphQL is better than REST based on the expenditure of effort for building out the first iteration of code for cherry picked scenarios is a first-year undergraduate CS101 study at best. Also, who funded this study? I want to know the actual costs of GraphQL. What are the tradeoffs with REST? What are the limitations? We're not going to hear from managers who are damage controlling their decisions, but maybe the developers paying for GraphQL adoption wouldn't mind sharing grievances? Now that money and reputations are at stake, I think that unfortunately it will be a while before the tech community starts admitting to mistakes, just as was done with adopting ORMs. The typical pitch about GraphQL is that it is intended to alleviate the pain of updating ORM dsl every time a change to an endpoint needs to be made to satisfy frontend requirements. Aren't updates to the GraphQL DSL replacing those made to the ORM? The problem hasn't been eliminated but replaced. One problem was replaced by another problem. If the worst part about working with a REST api with raw sql calls is that you have to make a few straightforward changes, while maintaining complete control of your sql, you're doing great.
- akra 6y agoFor me this is the point that I feel isn't well argued against by GraphQL proponents. Why if I'm a Javascript developer with probably a similar learning curve I couldn't just whip up a simple stateless frontend (in Node since its the same lang) and write the query in SQL? More to the point the skills learnt by doing so are more transferable. You also give your data store a chance to be more performant (e.g. better query plans for a typical DB) using that DSL to query the data store and there's a lot less complexity (components, libraries) in your solution. Also from what I've seen the approaches that may result in single ideal query plans in your database increase the complexity of GraphQL significantly with "GraphQL to SQL" compilers which still may not give tuned SQL especially with large graphs. Reminds me of using ORM's where often the generated SQL wasn't performant/slow. Even if it does work the complexity of your solution just increased - all for what? To translate one query language into another? There's also times where it may pay NOT to expose too much of your internal domain structure to public API's which I feel from a naive developer's perspective GraphQL could encourage (direct internal API structure to contract mappings). It feels, at least to me, that it is another abstraction layer that solves a problem that could also be solved at the org level. If there's suddenly a use case that requires a tuned query/algorithm/index as well (happens a lot from my experience) then its easy to add as a separate endpoint and test for regression test against other endpoints/use cases supported.
- brimstedt 6y agoI think one problem of gql relates to caching. Using rest, it's dead easy to enable caching on load balancer or CDN level with background updates. But with graphql- it's not so trivial. Youll have to do workarounds by caching POST requests (which imo is bad practice) or use GET requests, which might not work because the URL gets too long. Or use named queries, but then - what did you gain compared to rest? Another problem is that you expose internals and may more easily make yourself vulnerable to overload attacks. My two ören
- jensneuse 6y agoThe problems you described can be easily solved: https://wundergraph.com/features/caching https://wundergraph.com/features/caching What you gain is the flexibility of GraphQL together with the performance and cacheability of REST.
- altrunox 6y agoA while ago I decided to build another one of those Hacker News clone, and decided to use GraphQL, everything was fine, until I got at the comments... You cannot ask for all the children of a main comment or a thread, something like "give me all the comments and sub comments of thread X" is impossible, I was quite shocked because I read nowhere about this limitation, I solved it adding an extra field to my response adding a "father" field, so I needed to organize and sort the data at the front-end, instead of using an already sorted JSON like would be possible with rest. With all due respect, I find that most of GraphQL tests and examples return mostly simple data that is kinda easy anyways.
- xupybd 6y agoCould you elaborate please. I don't understand the issue surely you could model this on the backend and serve it via GraphQl?
- postalrat 6y agoI think he is saying graphql doesn't have recursion.
- altrunox 6y agoWell yes, that would be a better way to say it, no recursively nested objects, there is a Github discussion about it here: https://github.com/graphql/graphql-spec/issues/91 https://github.com/graphql/graphql-spec/issues/91 And if someone else is interested to take a look at my clone project (it's in Clojure), for the GraphQL issue you can search for "request recursively nested objects". https://www.giovanialtelino.com/project/hacker-news-graphql/ https://www.giovanialtelino.com/project/hacker-news-graphql/
- xupybd 6y agoThanks! That is really good to know. I wasn't aware of that limitation.
- juancn 6y agoThey are good for different use cases. There's no "better" without some very specific context.
- karmakaze 6y agoGraphQL has two notable advantages, neither of which are measured here. First by allowing the client to specify precisely what to retrieve the backend isn't catering to a specific client. This allows for decoupling so each team can develop quicker and with fewer changes down the road. Of course REST can also be decoupled only needing to follow conventions and defining the resource formats. What it doesn't provide is the second benefit of GraphQL which is eliminating round trips for accessing related resources. This is sometimes done by creating an intermediate 'BFF' service on the back end to serve requests as the client would like them but now that's sensitive to both client and REST API changes. In short, it's not about the development speed of the first client/server. If that were the case use gRPC etc, generate the interface, implement and you're done. It's about the supporting ongoing changes. Perhaps gRPC or similar will become prevalent enough to replace both REST and GraphQL.
- latte 6y agoGraphQL specifies schema and documentation, and implementations usually come with introspection tools, which is not the case for REST. It would be more fair to compare GraphQL to something like Swagger. That said, GraphQL libraries and tooling tend to be less fragmented and more ready to use than for equivalent REST stacks, which makes development much easier. A simple API built in Python with Graphene looks terse and declarative, while doing the same with Django REST Framework requires adding pages of plumbing code to build an equivalent REST API. Re: GraphQL being a pain for a backend development - I don't quite understand that argument. If you want to keep a tighter control over the schema, you can have it - the API schema does not need to be a reflection of the underlying data schema with all its relationships - it should be the front-end developer's job to convince you that this or that complex relationship needs to be exposed via GraphQL and let you make sure that it's served efficiently.
- CuriouslyC 6y agoGraphQL is trendy, but unless you need to maintain a lot of different versions of your API it doesn't really seem worth the investment.
- SkyPuncher 6y agoWe're exploring GraphQL because of the performance benefits of letting the client easily choose what it needs in the response data. The most prominent use case is lean list views and rich detail views. It's also helpful in views where related data is surfaced in detail. It can be done with REST, but there are enough edge cases that it's easier to simply follow a standard.
- bitL 6y agoI always think about GraphQL as pushing versioning into the future when it's either: 1) the product is dead 2) original folks moved on 3) "it's no longer my problem" The if-then-else spaghetti code it creates on the back-end whenever an API breaking change is needed is always cute.
- ummonk 6y agoAny sufficiently complex REST application ends up approximating a GraphQL-like API, just one that is ad-hoc / handrolled.
- dnautics 6y agoSerious question: given how difficult correctly parsing SELECT commands (and avoiding SQLi and other horrible issues like db parser impl bugs) is, why hasn't someone implemented a db whose query language is graphQL?
- yen223 6y agoThere's some activity in this space. Hasura uses a GraphQL-SQL compiler to generate Postgres SQL queries directly from a graphql query: https://hasura.io/ https://hasura.io/ FaunaDB, EdgeDB and DGraph are examples of databases that expose a GraphQL API.
- ChrisMarshallNY 6y agoI have never implemented GraphQL, so I can't speak from experience, there, but it does look pretty cool (if a bit "heavy"). I have implemented REST. I don't like "pure" REST, where POST, PATCH, and PUT statements are submitted as XML and/or JSON. I tend to do what I term "REST-like," sort of the way most APIs seem to do, these days, where the sending methods are done similar to standard URI GET/POST stuff (URI arguments). I tend to have responses come back as both JSON and XML, with a translator between them. XML is useful, because I can publish a schema, but otherwise, I prefer JSON. But REST-like is quite simple. I don't need to bring in any dependencies to provide the API, so it's fast and lightweight. But then, I have fairly humble servers. I suspect that GraphQL would be something I'd want for more ambitious servers.
- mlthoughts2018 6y agoThis is comically meaningless as far as evidence for making a decision goes. It reminds me of the various garbage studies purporting to show that functional programming leads to lower defect rates.
- ChicagoDave 6y agoGeneralizing integrations obfuscates business models, creating complexity. Both REST and GraphQL are convenient in the short term, but will hide important interactions over time.
- systemvoltage 6y agoThink about an API like a control panel for a machine. It is precisely designed for an operator abstracting away the details of the machine's electrical schematic and every component. It is user focused. GraphQL is like opening up the entire machine, stripping off the panels and working on live circuits. IMO GraphQL is great to quickly develop something. If your front-end is making 18 queries to REST API and you're making a case for how awesome GraphQL is, I think perhaps your REST API design needs to be properly thought out. I personally like to start with GraphQL, once everything is ready and I know what I want, write proper API endpoints. They can be REST-ful or REST-less. One API call for one function the front-end needs to perform. If the wiring in the machine changes and need fancy brushless motors are added, the operator doesn't need to worry about it. They can always replace the control panel with a new v2 version if they want additional features, but we guarantee that v1 version will continue to function. This is beautiful design. APIs don't have to be REST-ful and they should not be some kind of an analog of the backend database schema. API - it is in the name, "Interface".
- lukeramsden 6y ago> IMO GraphQL is great to quickly develop something. If your front-end is making 18 queries to REST API and you're making a case for how awesome GraphQL is, I think perhaps your REST API design needs to be properly thought out. I personally like to start with GraphQL, once everything is ready and I know what I want, write proper API endpoints. They can be REST-ful or REST-less. One API call for one function the front-end needs to perform. I think a good way of doing this is to use Postgraphile/Hasura to make a quick and easy GQL API, and then when you move to your "proper API endpoints", you can use Postgraphile in schema-only mode [0] at first, and then you have the ability to arbitrarily change endpoints to use custom SQL queries instead of using Postgraphile to build your query, while leaving other, simpler endpoints to still use Postgraphile. [0] https://www.graphile.org/postgraphile/usage-schema/ https://www.graphile.org/postgraphile/usage-schema/
- systemvoltage 6y agoThat's very helpful, thank you!
- vyrotek 6y agoOut of all the API implementations I've created in my career I've had the most success implementing BFF (Backends for Frontends) with simple RPC'ish endpoints. Everything else never quite fit right and wasted so many hours. https://samnewman.io/patterns/architectural/bff/ https://samnewman.io/patterns/architectural/bff/
- fastball 6y agoIsn't that effectively what GraphQL is supposed to be?
- vyrotek 6y agoNot specifically but it can could be used for it. GraphQL just a message spec (like dare I say, SOAP). But if you use it with BFF then the value of the dynamic query aspects seems less valuable. With a BFF your App/UI and endpoints can be tightly coupled. If a specific page/component/action needs data structured in a specific way then you just make the endpoint do exactly that. You can accomplish this over GraphQL but it seems like an unnecessary extra layer at that point.
- FpUser 6y agoOn my servers I do away with either. Instead client submits JSON object and gets JSON answer. Simple HTTP based RPC. But my servers of course are not some generic storage of knowledge for mining. Instead they're doing some particular processing and administration. So clients are not given as much freedom as in GraphQL. And I am free from headache of implementing some generic backend query service for no benefit.
- nickk314 6y agoIn my experience it's a lot easier to write performant, scaleable, and secure GraphQL API's than REST API's. Rest is a constant struggle between complexity, functionality and authorisation. The more flexible a REST API becomes, the more it becomes like GraphQL minus the standardisation. I wrote a blog [1] on writing GraphQL API's in TypeScript. It focuses particularly on authorisation and relations. [1] https://dev.to/nickkelly314/writing-a-graphql-typescript-server-in-nodejs-1n7e https://dev.to/nickkelly314/writing-a-graphql-typescript-ser...
- darepublic 6y agoThere is some kind of toast on this site that never goes away telling me all kinds of info I care nothing about (new member, so and so bookmarked this etc). I would like to fallaciously suggest that only a site with such poor judgement would host papers such as this that come to such erroneous conclusions
- dastx 6y agoIt is extremely distracting from the main content too. Whoever though this idea was good, needs to re-evaluate their decisions.
- rwoerz 6y agoGraphQL vs. REST somewhat resembles SQL vs. (document-oriented) NoSQL. If you can agree with your clients on certain access patterns (queries), you can design your RESTful API and your database collections, respectively, to suit these. If clients want full flexibility in what they query and avoid over-/underfetching, GraphQL and SQL (databases) might be better.
- danielrhodes 6y agoGraphQL is great to iterate with once you have built up the schema. However, after some time your queries will stop evolving and at that point you are better off with a REST API for the security and performance benefits.
- TeeWEE 6y agoREST without a IDL language with a schema definition is < GraphQL But things like OpenAPI =< GraphQL GraphQL has some disadvantages thought, due to the graph setup.
- ralusek 6y agoMy problem with graphql always comes down to permissions and performance. I feel like we went through the thought process of: okay, front ends are smart enough to ask for the data that they want, so why not just let them structure their own queries? But my problem is, the only time a client is smart and and to just ask for whatever they want us if I'm building an admin application, otherwise, all sorts of access control needs to be added to various levels of most queries, something I've never felt as though GraphQL handles well. Then there's the performance stuff, hitting caches or doing joins, it's much harder to make a GraphQL backend know when it can do these things, short of simple cache lookups by very limited keys. With REST, I'm somewhere in the middle. I'm saying, okay, these are the resources, and these are the actions. You might get a little more or a little less data than you wanted with your response, but I know exactly what you're getting, can optimize it, and test the shit out of it. I'm by no means resistant to new technology, I have just never worked on a project that avoided these pitfalls.
- cryptica 6y agoThe real cost of GraphQL is resource usage/performance on the backend. On the development side, the cost is that GraphQL allows developers to get away with writing really messy code whereas REST basically forces them to follow a more structured approach with better separation of concerns between components (to mirror the separation of concerns which REST endpoints naturally have). But I don't think this concern is that important because developers CAN design good software with either approach if they have the right mindset.
- collyw 6y agoWon't graphql shift a lot of the logic to the frontend? Personally I don't like having businesses logic in the frontend (though I have had "discussions" with other devs who believe it is not problem to have logic scattered about your app).
- Communitivity 6y agoThe two are not exclusionary. For me it is like having a higher abstraction API that provides for 80% of client developer needs, and a 'closer to the metal' API that provides for the remaining 20%. REST gives the popular/frequent queries optimized and canned, while GraphQL gives the power to create completely custom adhoc queries as needed. If you are creating a data service then I think you really need to have both. Which you do, and how much of it, is more likely to be dictated by time and budget. Many will need to figure out who their 80% audience is and prioritize based on that. Still a few REST services can be done, then GraphQL added with not mutators, then add mutators and more queryable data, etc. Start with the bare bones, just like you would a startup MVP and grow organically from there.