DEV Community

Cover image for Upgrade your JSON Endpoints with GraphQL
Shriji
Shriji

Posted on

Upgrade your JSON Endpoints with GraphQL

GraphQL is awesome and you can save a lot of time while developing frontend (No callback hell) and I am going to teach you how to convert a RESTful API endpoint into a GraphQL endpoint in a very easy way. This could be your boilerplate for your already existing JSON endpoints. For this example I am choosing https://coronavirus-19-api.herokuapp.com/countries/ endpoint. However I am not covering deep concepts in GraphQL.

Prerequisites:

  1/ REST endpoint (https://coronavirus-19-api.herokuapp.com/countries/{country}).
  2/ NodeJS. (graphql-yoga and good old node-fetch).
Enter fullscreen mode Exit fullscreen mode

Let’s look at the basic structure of the endpoint.

https://coronavirus-19-api.herokuapp.com/countries/usa
Returns:
JSON

Now we know the API can accept a country(usa,india,germany.., etc,.) in the end to spit out data of that particular country.

Now we know for sure all the endpoints have a certain structure, this in GraphQL is similar to schema which are those objects that you can fetch from a service so it is clear we can query countries to obtain data from the JSON endpoint.

We are using the graphql-yoga from (https://www.npmjs.com/package/graphql-yoga) and we will modify the example they have here.(also has a hello world example).

We need to write anything in the endpoint to its data type. For example
"country":"USA" will become country: String and the rest are clearly integers so its Int.

Congratulations you have done the first steps to convert a JSON’s endpoint to a GraphQL schema.

Convert to schema

Now we are going to write the resolver for GraphQL. Resolvers are responsible for giving you the data from a remote endpoint. Essentially they are your query handlers.

We have to supply a name for the query and arguments it can accept and in our case its the country and has type String.

Query and Resolver

Now it looks good and we can check out on localhost:4000

GraphQL Playground
Success you have made it. Now we can use GraphQL on any front-end frameworks using the https://www.npmjs.com/package/apollo-boost.

Here is the github repo of this post. https://github.com/peopledrivemecrazy/json-to-graphql

Enjoy.

Top comments (0)