106 points · by makaimc · 3y ago · 96 comments
- 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_...
- REST by default
- everything else might be an option, but you need to justify it with specific reasons.
Also, having a JS-driven front end or multiple teams is not an automatic justification for the complexity of GraphQL.
GraphQL is a huge burden, for very little practical gain. Most companies have very small number of examples of conflict areas where queries need to be optimized, and for the most part, these can be resolved through smarter front-end engineering (like not throwing React at CRUD websites).
It's amazing how we managed to build large-scale websites with essentially all modern functionality without all of this stuff for years and years, and only since 2012 or so have these tools become "necessary" (and I'm being generous with 2012...it's more recent than that).
I’ve recently been bolting graphql support onto a midsize legacy webapp with the goal of making native mobile apps easier, and so far I’ve been finding it remarkably simple and delightful — In fact implementing a graphql API so that the clients can specify which data they want for themselves has taken less time than all the design dicsussions about what a REST API could potentially look like…
(edit: originally I asked how it was a burden, but after refreshing the page I see this was already discussed in another subthread, so I’ll just throw in my anecdote without asking any question :) )
I will freely admit that, depending on the size of the team and the scale of the app, YMMV. For example, if you're the only person working on a legacy app that isn't under high load or lots of regular change, it probably doesn't matter what technology you use. At the extreme other end, the best tech in the world can be an impossible lift for a high-load service with a huge team supporting it.
Most of the parasitic complexity, in my experience, comes not from GQL itself, so much as the downstream burdens that come with maintaining the infrastructure needed to service the GQL. Everything being a POST, for example -- hope you don't like cacheing!
We use Hasura to provide GraphQL and find the exact opposite.
* Need to filter by X? Already done.
* Want to join two different entities? Done.
* Pagination? Done.
* Aggregation? Done.
* Security? Done, just set it.
* Streaming data? Done.
We don't have traditional API code, and yet have an API is more sophisticated and powerful than any API I've built professionally.
Shameless plug, I'd love to get feedback if you have the time to try it out.
[0]: https://docs.wundergraph.com/docs/features/graphql-to-json-r...
Look, maybe this is totally appropriate for your application domain. I don't know. But this kind of "power" is immensely complex. We have to be honest about the costs.
I have to keep reminding people that essentially all functionality of the modern web existed prior to 2012.
Also, as I understand it, when implemented properly, you can get more complex (?) data back. For example, instead of getting 10 orders, and then 10 more requests for the items for each order, you can make a single request and get both in a single response.
I believe both concepts apply to creates / updates as well.
Sort of (the sibling comment explains well why this example is an illusion). But even if this were an advantage, you have to implement the logic (simple in this case, but not so simple once people go hog-wild with the GQL). Also, I don't think I've ever had a situation in my career where loading name and price is a significant burden over either field individually. On the other hand, it's a huge burden to have to implement the back-end system that supports a fully orthogonal, structured query language for the UI.
To be fully charitable to the argument you're making, probably the real reason people do this is because they want to decouple development between Team UI and Team Product and Team Pricing, and it's just "easier" to expose "web SQL" to Team UI and let them go nuts, rather than sitting down with them an exposing targeted endpoints that give them exactly what they need.
...but now you have N problems. Your web app has become an ad-hoc distributed query language executor, and you have to think about the semantics and load implications of all of that.
If your user has authorization to access this extra data, the actual cost of sending those extra fields properties over the wire is ridiculously trivial.
Think a kilobyte or two, if not a few bytes.
Any justification you think you have for just sending the name + price is utter bullshit. You would save vastly more in bandwidth by not sending whatever dumb graphql code you wrote as part of your front-end build.
That is, unless you are Facebook or Google and have already optimized the hell out of your front-end libraries.
Which I guarantee you aren't and haven't done.
* your teams will now spend a big portion of their time thinking about GQL primitives and mapping and syntax (oh my) and otherwise caring for and feeding this beast.
* you still haven't solved the underlying problem -- you still have to figure out why your GQL requests are hammering the back-end(s...let's not forget that a lot of this stuff came from poor decision-making re: microservices!), only now it's indirected and harder to optimize.
* ...oops, you forgot to implement all the corner cases of your GQL schema! Go back to 1 and start over.
Say what you will about REST, but the syntax is dead simple, it takes about 15 minutes to learn, and the semantics are crystal clear. Whatever complexity remains is actual complexity in your problem or org structure, and you should probably just fix that instead of trying to find magical tech beans to abstract the problem away.
- GQL allows unbounded arbitrary queries. The awkward workarounds turn it into REST with none of REST semantics
- default query method (POST) cannot be cached by literally anything in the infrastructure because POST is not cacheable by definition. The awkward workarounds require you to parse and look up fields in both request and response. Both of them arbitrarily large.
- instead of delegating requests to optimized queries (db or services) you now collect all that data manually, in-memory, on the server with little to no insight into what the data is, and how to optimize its retrieval
- default types doesn't provide useful primitives like dates
- you now have to keep up with evolution of every single microservices you depend on
There's more that I've forgotten.
It's really good for building internal tools that usually have different requirements than what existing APIs provide you
My experience in doing so is limited, but I do know that this synchronization tends to be difficult and really like the idea of an explicit contract-based synchronization strategy.
It seems like a very big potential benefit but again, I don’t have enough direct experience doing too so be willing to put much stake in defending it.
But when that happened, what it really told me was that it was time to introduce a new endpoint and refactor the code to adapt to the change in use case. Painful? Sure. But so are the downstream consequences of converting everything in your system to an arbitrary query executor.
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.
- it's not about performance
- OpenAPI needs and has tooling (it just doesn't work) - think about documentation, client/server code and evolution support for forward/backward compatibility, type safety, etc.
- you can build monoliths and microservices with both
- gRPC / protobuf gives you a pragmatic separation of concerns (and typing among other things)
- gRPC allows exposing REST/OpenAPI with defualt tooling and it works
- there's an extensive set of best practices that combine the best of both worlds - just read https://google.aip.dev/
- if the workd prefers GraphQL, you're out of luck
- gRPC / protobuf help you focus on the actual contract and make everything else (that's 90% of time) a non-problem.
---
Disclaimer: I'm in the grpc (and protobuf) camp and have built APIs with REST, Thrift and gRPC/Protobuf for more than 15 years (gRPC mostly last 5 years) As an infrastructure startup we have to both expose and consume both REST and gRPC.
If you build APIs and decide to handle the above manually - you must feel productive doing work that compilers and code automation tools have been invented for. However tooling should automate it for you.
+1 on the terrible state of grpc cli tooling (unless you are already working at a faang).
-1 on Web proxy - As mentioned before I actually find that seperating a http "transaltion" gateway from your core biz logic is a win in my mind.
+1 On way too many microservices. IMO whether you use GRPC or OA, you can build monoliths or way too many microservices. I have not felt GRPC explicitly enforced that. What I did get from grpc is the logical seperation with grpc (you can still bundle multiple services in a single binary vs as seperate microservices) if you want. With grpc (nay proto spec) building a service becomes a logical exercise over how do i structure URLs vs what verbs to use etc.
PS: On a completely diff note I actually like your approach to isomorphic types. My switching to the grpc side was largely motivated by this single source of truth from whence all layer specific types came forth from!
example: https://www.freecodecamp.org/news/a-new-approach-to-mocking-...
In contrast, an OpenAPI is a REST-ish API with an OpenAPI specification. It's not as dynamic as REST, it's not Hypermedia, it's much more "JSON over HTTP" but also not exactly RPC.
Look at https://api.github.com/users/octocat
Or the OpenID Connect and /.well-known/openid-configuration https://openid.net/specs/openid-connect-discovery-1_0.html
And while I might be invoking scotsmen, very few things look like https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arc... and so are best described as "REST like" or "RESTish".
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.
I’ve always thought these posts were for non-technical product buyers and decision makers.
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. Just like the stylesheet for this website is a resource identified by https://news.ycombinator.com/news.css.
* It may be, if that's the _representation_ you want.
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.
With nobody thinking about the interface, you are left with the classical dilemma between usability and security. And all GraphQL tooling seems to floor their feet on the usability side.
Other than that, it seems that the answer is just performing object-level authorization to ensure you never leak resources a user isn’t supposed to have access to. Depending on the framework you use this can be pretty straightforward…
But the point is that no, it's not straightforward; the authorization must be designed to fit your needs. If you are not designing it, you can be certain that it's broken.
Thats the killer feature.
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.
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.
I'd like something like GraphQL, but built on standard data formats.
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.
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.
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.
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.
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.
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.
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.
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.
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
> 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.
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.
Is there a better, more automatic way to generate GET and POST endpoints automatically when I create a new model?
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.
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.
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...
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.
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.h...
my understanding is that facebook whitelists their graphql queries but, last I looked, I didn't see security getting much attention around it...