GraphQL for new projects looks great ... buuuut how do you use it with that old backend cobbled together in Rails over the last bazillion years?
Can you write an async function that returns some data? Great! That's all GraphQL needs. 🤘
No seriously, it's that simple.
You can connect GraphQL to your REST API instead of the database. Create a small proxy and start using GraphQL on the frontend today. No backend changes required.
We explored this idea on a stream 👇
Out came a proof of concept that took a 37KB payload from our production API at Yup and turned it into this:
😍
Why wrap a production API in GraphQL
37KB for one request isn't even the biggest API payload we've got. It's just the most common 👉 our entire settings object.
Nobody even knows which of those fields are still in use. Can't remove any because you might break an old client.
So forever more every client gets every setting that any client in history ever needed.
With a GraphQL proxy, each client can take just what it needs.
It works like this:
- Client sends GraphQL query
- GraphQL proxy gets query and maps it to the
settings
resolver - Resolver makes
fetch()
request to API - API returns full settings object
- GraphQL machinery matches object to query
- Proxy returns only the requested data
Want to combine multiple API requests into one? Now you can! Just send 2 queries in 1 request.
Users get a faster app and lower bandwidth usage.
You get an easier coding experience on the client and you empower frontend engineers to make better decisions.
Worried about the overhead of a GraphQL proxy?
Many requests can be cached and don't even have to hit your real backend.
How to wrap a REST API with GraphQL
- Create a GraphQL server
- Write query resolvers that poke your API
- Build GraphQL type definitions from your payloads
That last part is tedious, I'm sorry.
Wittern et al talk about Generating GraphQL-Wrappers for REST APIs in a 2018 paper, but I haven't found a good implementation in the wild yet. Hasura looks like a great approach, but they convert your Postgres schema into a GraphQL API, not your client-facing API.
How related are your Postgres and your REST API really? I bet you build those payloads from SQL queries, environment variables, helper methods, and all sorts of stuff.
WalmartLabs created a JSON-to-GraphQL library that works well for a first pass. I used it on the stream.
You could create a crawler that goes through your API and builds GraphQL type definitions. 🤔
Build a proof-of-concept to impress your boss.
After harping on and on that we need GraphQL and it will solve many of our problems, my team started getting tired of my shit. We can't do it, it's too hard, we don't want to change the backend, we ... screw you I'm building it.
here's what I found
serverless.yml
Host on AWS Lambda so you don't have to deal with servers. Focus on the code.
Run sls deploy
and you get a server that runs your graphql.handler
method on every GET and POST request.
graphql.ts – Apollo AWS Lambda server
Apollo is great for building GraphQL servers. Good community support, integrates well with Lambda, great developer experience. 👌
This creates a GraphQL server. Send a POST request and it maps queries to resolvers. Send a GET request and you see an Apollo playground so you can try your queries.
schemas
Schemas represent the shape of your API.
This will take some manual work. I recommend a Query for every GET endpoint in your API and a Mutation for every POST/PUT/DELETE etc.
Then use something like the walmartlabs schema generator to build type definitions for each endpoint. Some might overlap and that's okay.
To keep code organized I recommend 1 schema file per endpoint – src/schema/Thing.ts
. Like this
There's 300 lines of this crap. You don't wanna write it by hand from scratch 😅
A crawler could be a good idea. Something you point at all the different endpoints and it collects those schema definitions.
You'll have to consolidate and clean up by hand.
combining all those schemas
Get all your schemas imported and into an array, pass them into ApolloServer as type definitions.
Query user
returns the User
model, settings
for Settings
etc. Build a mapping that makes sense for your API.
Remember that you can extend type
in any schema to extend existing types. Great for adding queries and mutations.
map queries to REST requests with resolvers
Resolvers are where you map queries to data. Any data from anywhere. 🤘
For my settings proof-of-concept, it looks like this:
An API wrapper helps with authentication, staying logged in as a user, and sending the right headers with each request.
The API.settings()
method sends a fetch request to /api/settings
and returns the payload.
Hardcoded to my dev machine because this is just a prototype. You'd want that to be a setting or environment variable of some sort.
The headers also are hardcoded and I stripped the token before sharing.
My login method also is quite ratchet. It uses a demo user's email/pass combination to fake logging into the server. 🤣
You'll need to figure this part out for yourself. Authentication depends on your backend implementation. You might not even need it for some requests.
And that's how you wrap your REST API in a GraphQL
- GraphQL server
- Turn payloads into schema
- Map queries to endpoints
Where it gets tricky is preserving end-user authentication. You'd need to get cookie/token information from the client or run the login process through your proxy.
Large POST requests could look weird too.
We have some endpoints that accept a JSON blob with tens of parameters. Several kilobytes of data. Stuffing all of that into mutation arguments feels funny.
Maybe you could have 1 parameter that accepts a JSON string 🤔
If you decide to go down this route, expect a schlep followed by "Yay we have GraphQL now" from everyone else on your team. You'll be their hero.
I think it's worth it.
Cheers,
~Swizec
Learned something new?
Want to become a high value JavaScript expert?
Here's how it works 👇
Leave your email and I'll send you an Interactive Modern JavaScript Cheatsheet 📖right away. After that you'll get thoughtfully written emails every week about React, JavaScript, and your career. Lessons learned over my 20 years in the industry working with companies ranging from tiny startups to Fortune5 behemoths.
Start with an interactive cheatsheet 📖
Then get thoughtful letters 💌 on mindsets, tactics, and technical skills for your career.
"Man, love your simple writing! Yours is the only email I open from marketers and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. 👌"
Have a burning question that you think I can answer? I don't have all of the answers, but I have some! Hit me up on twitter or book a 30min ama for in-depth help.
Ready to Stop copy pasting D3 examples and create data visualizations of your own? Learn how to build scalable dataviz components your whole team can understand with React for Data Visualization
Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.
Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first 💰 on the side with ServerlessReact.Dev
Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com
By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️