How to Do a Rest Post Request Using Apollo Client?

I know that we can also perform rest request using apollo, but I cant figure out how to do a post request, Can someone help me with it?

My REST post request endpoint is: <url>/transaction/getbyhash

Payload:

{"hash":"4e23f9e1d1729996de46fc94d28475b4614f101d72a98f221493f900dc33e0c2"}

Can someone please help me write the same request using apollo client and graphql-tag ?

1 Answer

You can use apollo-link-rest to call REST API inside your GraphQL queries.

E.g.

rest-api-server.ts:

import express from 'express';
import faker from 'faker';

const app = express();
const port = 3000;

app.use(express.json());
app.post('/api/transaction/getbyhash', (req, res) => {
  console.log(req.body);
  res.json({
    email: faker.internet.email(),
    name: faker.name.findName(),
  });
});

app.listen(port, () => console.log(`HTTP server is listening on ));

client.ts:

import { ApolloClient } from 'apollo-client';
import { RestLink } from 'apollo-link-rest';
import { InMemoryCache } from 'apollo-cache-inmemory';
import gql from 'graphql-tag';
import fetch from 'isomorphic-fetch';

const restLink = new RestLink({
  uri: '
  customFetch: fetch,
  headers: {
    'Content-Type': 'application/json',
  },
});

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

const getbyhashQuery = gql`
  fragment Payload on REST {
    hash: String
  }
  query Me($input: Payload!) {
    person(input: $input) @rest(type: "Person", method: "POST", path: "transaction/getbyhash") {
      email
      name
    }
  }
`;
const payload = { hash: '4e23f9e1d1729996de46fc94d28475b4614f101d72a98f221493f900dc33e0c2' };

client.query({ query: getbyhashQuery, variables: { input: payload } }).then((res) => {
  console.log(res.data);
});

The logs:

{
  person: {
    email: '',
    name: 'Miss Jaren Senger',
    __typename: 'Person'
  }
}

package versions:

"apollo-cache-inmemory": "^1.6.6",
"apollo-client": "^2.6.10",
"apollo-link": "^1.2.14",
"apollo-link-rest": "^0.7.3",
"graphql-anywhere": "^4.2.7",
"graphql": "^14.6.0",
"isomorphic-fetch": "^3.0.0",
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest