184 points · by gsvclass · 5y ago · 237 comments
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.
I wish there was a client side library that implemented GraphQL as an abstraction over REST, GraphQL or other backend APIs. It would be nice to use some of the GraphQLs query/join features across several backend services without those services having to change. Imagine being able to merge a vendor API that can provide a tracking number with FedEx's API, for example.
You can pretty easily (if you have experience with the GraphQL reference implementation in JavaScript) create a GraphQL layer that sits inside of the browser, with a schema created by the UI team, that executes calls to REST APIs to resolve the data.
You could think of it as an “ORM” for the browser, which seems cool, but I wouldn’t necessarily recommend this approach (though I have done it in the past) for two reasons:
1. The “graphql” library isn’t really optimized for size so it can add a bunch of overhead to your JavaScript bundles
2. One of the benefits of GraphQL is to combine multiple requests for related data into a single query to be sent from the browser. Yes, that makes the life of the backend developer harder as they try to optimize for performance, but it makes for less data/fewer requests over the wire to the client. If you stick GraphQL in the browser, you’ve now just moved your N+1 query across the internet.
If you really want to go down that road, Apollo offers a “plugin” to their GraphQL client that allows you to call multiple REST endpoints as if they were a single GraphQL endpoint (without embedding the actual “graphql” library in the browser): https://www.apollographql.com/docs/link/links/rest/
A better approach for what you’re looking for would be to schema stitching (which allows you to combine multiple GraphQL endpoints together and treat them as one. You can even combine that with your own schema definitions to mix in whatever backend sources you want; e.g. your vendor + FedEx REST APIs): https://www.graphql-tools.com/docs/stitch-combining-schemas
Or if you don’t want to do the work yourself, check out OneGraph, which uses schema-stitching to do exactly what you describe. It’s pretty cool: https://www.onegraph.com/
I think the bigger problem there is how those multiple REST calls map to your data stores. Very rarely will there be clean separation of data between endpoints, and the stateless nature of REST makes it harder to optimize each call -- meaning, there will almost certainly be redundant queries.
That said, with GraphQL, your front end dev may not realize they are executing the equivalent of many REST calls, which is another problem :) I wouldn't say it's harder to optimize if you look at the application as a whole, though.
I just grokked this very recently when I was reading up on Gatsby and the fact that they use GraphQL. I was confused for a bit because Gatsby is SSG, until I realized they merely use GraphQL as a generic way to query any JSON data you might have laying around, similarly to how getStaticProps() is employed in NextJS
On the server side, assuming you have a simple CRUD service in front of a DB, you can probably use a generic GraphQL-to-DB query language library and call it a day. If you have to expose a REST API, you need to understand what's stored in the DB and create some queries, make sure they are performant etc.
Now, if you have a complex service with heterogenous data sources that you want to present homogenously, then both REST and GraphQL will be much more difficult. But even then, with GraphQL you can leave most of the hard work of figuring out how to join efficiently on the client, while with REST it's your responsibility to ensure that the requests execute in a decent amount of time.
In my own company, we use GraphQL for internal communication between a few microservices because we need the flexibility, but we expose a REST API to users, because no one wants to learn how to write queries instead of doing a simple GET on an endpoint we already expose.
This is how I view graphql (despite not having used it). It seems better practice to keep the querying done in the backend and keep frontend for display logic more than anything. Seems like graphql will encourage business logic in the frontend (my current workplace has this problem and it is not something that should be encouraged).
This is a feeling on the problem space, and not based on any studies though, as I'm unaware of any studies trying to determine this.
GraphQL allows (limited) queries from the client.
GraphQL unlocks Frontend-acting-as-Product, or Product
At the cost of (hopefully) a smartly written decorator, a schema-based boilerplate, or a bunch of resolvers. And surely, I guess some raw performance and enforced abstraction.
If you go the whole hog, and make your client leverage the full query granuality, then it also costs some FE complexity .e.g Apollo. But you dont always need that aspect.
Is this good for your problem space? Depends. Is it great for some problem spaces, 100%
So every once in a while, the question comes up whether we shouldn't be using GraphQL for this, and every time we end up unsure where to start, how to implement it, or what the actual benefits would be. We control both front and back end, and REST works fine for us.
I guess if we ever want to make our back end usable by other applications, GraphQL might become more useful to us, but until then, it seems like it's mostly a lot of extra work and complexity that we don't need.
GraphQL seems most useful when you're using something that supports it out of the box.
Just need to figure out server-side validation now.
I may also be old and cranky and you should probably get off of my lawn.
Also, a much more minor issue, but when everything is a POST to a single endpoint, debugging network calls in Chrome/whatever dev tools is more of a pain in the ass. It’s a lot easy browsing through GET /users/124, DELETE /messages/456, etc., and instantly see what’s happening, than having every call be POST /graphql, and have to read through all the giant post bodies to figure out what’s going on.
IMO GraphQL is no better than all the other multitude of RPC frameworks that everyone eventually realizes are a snake pits of unnecessary complexity when compared to REST. It’s just newer, so people don’t hate it as much YET.
So its relative merits have a lot to do with how complicated a thing you're trying to do in the first place.
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.
If so, I do agree with that statement.
Perhaps that's my bias showing. Lately I've mostly been working in Java, a context where the words "easy" and "Web" rarely belong together in the same sentence.
Also the API provider had a "GraphQL is self-descriptive, go away" attitude when asked for documentation that made things worse.
It could be me (or my team), but we didn't find it easy at all to explore the API and find what we were looking for. We ended using a Python tool that generated some classes from the schema and, thanks to that, we managed to figure out the queries we needed to use in our Scala client. Not a fan.
Now actually implementing a server on the other hand is much more difficult.
I don't want to query. I want to submit a transaction for processing dammit.
Again though, it might just be a case of me being old and cranky and having to learn yet another query language.
In any case, we now have the graphql playground where you can prototype your queries with full autocomplete (based on the schema). I've done this with third party graphql APIs; it's stupidly easy and you don't need a lot of documentation generally.
We're using the Expedia implementation for Kotlin and Spring Boot. I have a suspicion that that setup might be lot easier to deal with than Appollo and node.js since it has the important feature of using reflection for creating the schema from code. I've not written a single line of graphql schema in nearly 6 months of creating dozens of graphql endpoints. We also use kotlinx serialization to generate cross platform parsing code in our multiplatform client (we use it on Android and in the browser and soon on IOS). So, this offloads a lot of hassle of dealing with schemas and parsing both client and server side that we used to have with REST based APIs. Maybe not the most common path but worth checking out if you are looking to get started with this stuff.
My process for adding a new endpoint:
1) write a function in a spring bean that implements the Mutation or Query marker interface. Spring Boot does the rest. It generates the schema at startup time and wires everything together.
2) start a dev server, prototype the new graphql query in the playground
3) paste the working query to a new function with a multi line string along with any model classes we need in our multiplatform (js, android, and soon ios native) client library and recompile that to add the new client code for the query.
4) update the dependency on our android and web projects (we use kotlin-js for our admin UI) to use it.
5) also add the new client to our integration test project so we can write some tests for the new endpoint. We have full end to end tests of our client and API. Our server uses some mocked databases and middleware when running the tests.
It's definitely not perfect; the Expedia implementation definitely has some quirks and limitations. Also, Kotlin multiplatform has been a bit of a moving target in the last few months (though a lot more usable as of Kotlin 1.4.x). But overall it's a great setup for a small team that has better things to do than crafting custom REST APIs.
In terms of performance, technically graphql is just an HTTP POST API on top of Spring Boot (for us at least). Yes, there's a bit of overhead for query processing on the server but most of your performance is otherwise exactly the same as it would otherwise be. You of course pay a price for crafting complicated queries. But that's the same price you pay for having poorly aligned UI and REST APIs where you end up making lots of REST calls because you did not design your API right (been there, done that). Graphql just allows you to iterate on that more easily. But it's not inherently slower in any way. We are currently not doing any federation but that's mostly because we have a monolith server instead of micro-services.
It just was not difficult to learn at all.
Besides, what do you call the parameter to fill the owner of the children? Fillchildrenowners? It’s nicer to work with if your API takes this into account.
- cause additional sql joins - or pull individual records from a cache (if it’s a small enough dataset) - or cause one additional DB query and save a network round trip.
Example:
/api/v2/discussions?sort=recent&expand=insertUser,updateUser,lastCommentUser,parentCategory
This would be a pretty extensive case but is very useful.
So, commonly, does a REST endpoint that observes HATEOAS (without which it is not REST.)
> I know there are tools like Swagger that solve this problem to some extent, but its not baked into the standard like with GraphQL.
REST is an architectural style, not a standard, but it is baked into the description of the architectural style.
I just pulled up Fielding's paper and couldn't find anything, but wikipedia has a reference to 'Hypermedia as the engine of application state' (HATEOAS).
But then again, I am not sure anyone actually writes systems like this. Very few people actually write REST systems and instead make REST-like APIs.
In the end you simply want to interact with the client or server and procedure calls do just that. I honestly do not see the use in over complicating that.
But the jsonrpc endpoint had good documentation and the client library didn't feel alien to the project, like a big query string embedded in the client code.
I wonder why jsonrpc is not used more often; but I guess compared to a REST API, the client may be more complicated.
You write the moral equivelent of __attribute__((graphql)) on your code, and boom, you can query it. You want mutations? __attribute__((graphql_root_mutation)). If your object is stored in TAO, everything works perfect. You can add custom fields or even custom objects implemented in PHP that can do whatever the hell they want.
You never have to think about a database. And you barely even have to think about security if you're using pre-existing objects, the rules for which users should be allowed to see which objects are written in one centralized place and enforced everywhere in the codebase, graphql included.
Of course, it only works that well because there are multiple ~20-30 person teams maintaining that infrastructure. And GraphQL was designed with Facebook's infrastructure in mind.
Outside of Facebook, I cannot see myself using GraphQL for any reason.
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.
My experience is that almost all REST APIs are like that, give or take some documentation. Though I have read about both, I have never worked with a JSON schema or Open API api. I have conservatively worked at least a hundred REST APIs, including both public and private ones.
I’m mildly optimistic about GraphQL, but without a doubt I think one of the best parts is that all GraphQL APIs have typed schemas. There is no discretion on the part of the API provider.
This is similar to a debate regarding programming languages. Some people like more restrictive languages, because they don’t trust others or themselves to reliably use good discretion in the use of powerful features or omission of optional safety checks like types.
For me, it's not even that. It's that I've discovered that, even when used with discretion, the simple presence of powerful features still makes it harder to reason about how things work. Discretion around powerful features isn't a one-and-done thing; it's an ongoing process of double-checking and verifying for yourself whether that feature is being used properly every time you touch or interact with code that uses it.
A common thread in many seminal papers and essays in the history of programming languages ("Can Programming be Liberated from the Von Neumann Style", "GOTO Statement considered harmful", "Lambda: The Ultimate GOTO", to name a few.) is that, ironically enough, when you take a bird's eye look at things, reducing the power of the tools tends to increase the power of the programmer.
I should say, I'm not meaning that to be a statement in favor of static or dynamic typing; I try to stay out of that debate.[1] To me, the real problem with JSON is that, at least under typical usage, it tends to be weakly typed. (Which is a powerful feature; strong typing is a way of restricting what you can do.) JSON's type system is less expressive than that of basically any well-known programming language, including JavaScript itself, and, out of necessity, people tend to deal with that by overloading its types in ways that may force consumers to use out-of-band knowledge to interpret a message properly. This has a tendency to happen even in the presence of OpenAPI specs or JSON schemata.
[1] Though I'll take this chance to link https://cdsmith.wordpress.com/2011/01/09/an-old-article-i-wr...
Unless you are writing custom REST endpoints for every aspect of your UI, most formulation of what data a consumer needs will usually resolve in multiple trips to the server. So, you either scale out by having custom REST endpoints to handle each case of this (which both feels odd and presumably won't scale very well), or you take advantage of GraphQL doing this natively.
Wouldn't that be the normal way to implement a REST API?
For example, take a small blog, that holds several posts, each with an author.
In GraphQL, you could fetch all the posts, and all info related to the author in the same query (without any new, funny business).
In REST, if you wanted this in a single query, you'd need to define some endpoint like /post-and-authors-list that fetches all the posts and complete author information for each post, whereas most REST implementations would probably involve a small set of CRUD steps on all posts, and then several queries to fetch each author for further information as well (based on the author ID in the post).
So it's not that REST can't implement anything GraphQL wants to implement, but there is a lot more work involved, is harder to scale out with developers, etc.
In other words, as you say, if there's a schema with the REST API, GraphQL loses one of what the authors claim as a key benefit.
It's not like if there is a schema with a REST API, the GraphQL alternative becomes un-typed.
I see also the paper says, in bold, "it is unfair to attribute the gains observed with GraphQL only to the IDE", but elsewhere they trumpet the ability of the IDE to interpret and enforce the schema as significant. And again, we can accept that the feature is useful without conceding that GraphQL has the advantage. We could just as well have an IDE that understands OpenAPI specs an accomplish the same thing.
[1] https://en.wikipedia.org/wiki/Swagger_(software) [2] https://en.wikipedia.org/wiki/GraphQL
we do happen to do more interesting things elsewhere (GPGPU, columnar streaming analytics, reactive frontend, ...), so like sharp edges when a 10X+ lift, but ended up backing up on this layer as it was adding complexity w immature layers vs what felt like similar perceived benefits from reliable boring stuff. it doesn't scratch all our itches, but the big ones are at a layer above/beyond graphql vs rest (eg, auth)
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".
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.
We're currently dealing with this on a REST API right now. If you have highly relational data, you run N+1 risks regardless. I think people misplace blame on REST/GraphQL when they will have fundamental data issues either way.
We're exploring a few ways of solving it, but they honestly all resemble GraphQL.
Now the product folks want to add comments, so you add a new comments field on your article, with a new field resolver that queries the database for comments like SELECT * FROM comments WHERE article_id = ?.
This works great when viewing a single article: the frontend makes a single query to the GraphQL API, which makes 2 database queries: one for the article details and one for the comments
But then the product folks want to update the article search page with a expandable comment section for each article, so you can preview the comments for an article. Easy enough, all you have to do is add the comment field to the GraphQL query for the article search page, it's a GraphQL success story!
But now when the article search page loads, it runs 1 GraphQL query that retrieves 20 articles, and for each one it runs the SQL query to load comments. So instead of making 2 database queries it's 21.
Now we have performance scaling along with the number of results on the page, which is not ideal.
articles = Article.load(limit=10)
for article in articles:
# .author implicitly runs a query
author_name = article.author.name
This can be avoided in ORMs providing prefetching (e.g. `Article.load(eager_load='author')`).[0] https://nhost.io
It's pretty impressive too. For any deeply-nested query, like fetching the 1-to-many children of 1-to-many children of some entity, a lot of ORMs will often have to resort to doing N+1 queries, which adds a surprising amount of latency to a request.
Ember Data solves almost everything so you can focus on features and deliver the app in no time.
That's one thing that's great about Apollo; it's not too tied to any other tech / framework (except GraphQL, of course).
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.
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.
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.
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.
Well, it was published/presented at Working IEEE/IFIP Conference on Software Architecture - https://ieeexplore.ieee.org/abstract/document/9101226 - though I have no idea on how respectable that conference is.
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.
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.
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.
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/
[2] - https://htmx.org
API adoption was low in the end - teams in the end wanted libraries rather than a well-defined representation with embedded hyperlinks. Every consumer I heard about simply parsed the JSON bits they wanted from responses and hard-coded URL links in their client apps.
I enjoyed the design and writing of the app - I used Clojure and the liberator library. Probably a wasted effort of engineering in the end. Totally fun project to implement though.
Exactly. HATEOAS is for humans:
https://intercoolerjs.org/2016/05/08/hatoeas-is-for-humans.h...
Therefore JSON isn't an appropriate transport for a REST-ful API.
I understand that 99% of the internet disagrees with me.
Especially:
* uniform interface
* hypertext
And even more especially how JSON does not meet the requirements?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.
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.
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.
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.
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.
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.
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.
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.
{
"products": {
"abc123": {
"id": "abc123",
"name": "Some Widget"
},
"def456": {
"id": "def456",
"name" "Some Other Widget"
}
},
"images": {
"xyzabc": {
"id": "xyzabc",
"product_id": "abc123"
"url": "https://example.com/xyzabc"
}
},
"reviews": {
"4": {
"id": "4",
"product_id": "abc123",
"user_id": "hjk453"
"review": "This thing sucks!"
}
"15": {
"id": "15",
"product_id": "abc123"
"user_id": "pos999"
"review": "I love this thing!"
}
},
"users": {
"hjk453": {
"id": "hjk453",
"handle": "somebody",
"name": "Some Body"
},
"pos999": {
"id": "pos999",
"handle": "someone",
"name": "Some One"
}
}
}My endpoints take a 'fields' parameter... and those fields can themselves be serialized objects.
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.
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.
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.
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.
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".
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.
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.
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.
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.
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/
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.
Hasura uses a GraphQL-SQL compiler to generate Postgres SQL queries directly from a graphql query: https://hasura.io/
FaunaDB, EdgeDB and DGraph are examples of databases that expose a GraphQL API.
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.
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
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.
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).
Both REST and GraphQL are convenient in the short term, but will hide important interactions over time.
But things like OpenAPI =< GraphQL
GraphQL has some disadvantages thought, due to the graph setup.
GraphQL isn't a magic bullet; you still need to implement/define how the data is returned.
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.
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-ser...