Should you use GraphQL or REST?
GraphQL is a powerful query language for the backend. It lets you fetch exactly the data you need no more, no less, and no extra round trips.
REST, on the other hand, uses fixed endpoints and HTTP verbs. You request endpoints with different HTTP verbs and fetch predefined data, whether you need it all or not. It's simpler and easier to implement.
So, when should you use which?
- Go for GraphQL if you've ever been frustrated by fetching too much or too little data from an API, want to avoid endless round trips, or need to deal with complex data relations.
- Use REST for simpler apps where the endpoints are clearly defined, and you don't mind loading extra data, making multiple requests, or just want to ship something fast.
Personal note: When you know what you're doing, GraphQL is often more productive and faster to work with. The initial setup might take a bit more time but it pays off.
Recommendation: GraphQL.
Once I switched to GraphQL, I couldn't go back you really should give it a try at least once.
N+1 Problem
One of the first issues you'll face with GraphQL is the N+1 problem. Since each field commonly resolves separately, requesting users and their posts might trigger multiple DB queries one for all users, and then one query per user to fetch their posts.
This isn't necessarily a bug it's just how GraphQL works.
There are many solutions available most popular one is DataLoader. It helps batch database queries to avoid the n+1 issue and improves performance significantly.
I'll write about DataLoader
in detail in the future, inshallah.