DEV Community 👩‍💻👨‍💻

Cover image for Wrap any rest API with GraphQL from the frontend
Wally Frikh
Wally Frikh

Posted on

Wrap any rest API with GraphQL from the frontend

After discussing with my direct network about this topic and how this could be achieved, I noticed that some people might still think that this is impossible or really difficult to put in place.

Following the link at the end of this post, will guide you to my personal blog where I will raise few options that will allow you to interact with your current rest API endpoint with a GraphQL client even if nothing is ready on the backend side.

So, if you have less than 5 minutes to discovers how this could be done, check this post in my personal blog here

If you are in a hurry, you can just read the code below.

import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { RestLink } from 'apollo-link-rest';
import { gql } from 'apollo-boost';
// the gql import above is supposed to be like the following
// import { gql } from 'graphql-tag';
// For some reason it's not working in codesandbox and I just found this workaround

// setup your `RestLink` with your endpoint
const restLink = new RestLink({ 
  uri: "https://rickandmortyapi.com/api",
  responseTransformer: async response => response.json().then(data => data.results) ,
});

// setup your client
const client = new ApolloClient({
  link: restLink,
  cache: new InMemoryCache(),
});

const query = gql`
  query allcharacters {
    characters @rest(type: "Character", path: "/character") {
      name
    }
  }
`;

// Invoke the query and log the person's name
client.query({ query }).then(response => {
  console.log(response.data.characters);
});
Enter fullscreen mode Exit fullscreen mode

As said above more details and useful links about this topic, in my personal blog post

Hope it will help you to crack the subject

Wally

Top comments (2)

Collapse
akashkaintura profile image
AKASH KAINTURA

okay that's Cool.
But I am working with same approach but with Laravel we wrap api into gatsby from backend.

Collapse
wally profile image
Wally Frikh Author

Cool ^^

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.