Search code examples
restapolloapollo-clientreact-apolloapollo-server

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 ?


Solution

  • 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 http://localhost:${port}`));
    

    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: 'http://localhost:3000/api/',
      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: 'Bryce34@gmail.com',
        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",