Home > Software engineering >  How to get data from REST API using a graphql
How to get data from REST API using a graphql

Time:11-30

How to get data from REST API using a graphql query

How to get data from REST API using a graphql

CodePudding user response:

Generally, it is easier to make queries to a REST API in the traditional RESTful manner and GraphQl only to GraphQL. However, I'm going to assume that in your case, you have a GraphQL server running and you are trying to query a public API that is only available using REST. There are a few different ways to do this, but both require some knowledge of the data schema which you are querying.

If you want to do this client-side, you can make a typical REST query using axios, fetch, got, or whatever other HTTP agent you prefer and incorporate that data in the UI with your GraphQL data. Apollo Client offers an option to distinguish data not from the GraphQL API by including @client on specific fields in your query. This helps maintain the cache and keep your global schema in sync.

If you already have a GraphQL server running, you need to define a custom schema and resolvers to match the data fetched from the REST API. Here is a very small example using express-graphql to create a GraphQL endpoint using the SpaceX REST API.

const {
  GraphQLObjectType,
  GraphQLInt,
  GraphQLString,
  GraphQLBoolean,
  GraphQLList,
  GraphQLSchema
} = require('graphql');

// Launch Type
const LaunchType = new GraphQLObjectType({
  name: 'Launch',
  fields: () => ({
    flight_number: { type: GraphQLInt },
    mission_name: { type: GraphQLString },
    launch_year: { type: GraphQLString },
    launch_date_local: { type: GraphQLString },
    launch_success: { type: GraphQLBoolean }
  })
});

const LaunchQuery = new GraphQLObjectType({
 name: 'LaunchQueryType',
 fields: {
  launches: {
   type: new GraphQLList(LaunchType),
    resolve(parent, args) {
     return axios
     .get('https://api.spacexdata.com/v4/launches')
     .then(res => res.data);
     }
    }
   }
});

module.exports = new GraphQLSchema({query: LaunchQuery});

You could then incorporate this with your other resolvers to complete your GraphQL endpoint.

CodePudding user response:

You can't get data from a REST API using a GraphQL query. GraphQL and REST are 2 different protocols. You'll need to use HTTP to query a REST API, and GraphQL to query a GraphQL api.

  • Related