Apollo client

In the previous post for Querying data with GraphQL we used a ASP.NET Core HTTP client. But as I have mentioned there is an option to fetch the data with JavaScript using a client called Apollo.

Apollo is a very good choice of library if you are building an application with GraphQL because of its flexibility and simple use. Like it is written in its documentation it is a complete platform for implementing a graph over your data. It includes two runtime libraries, Apollo Server and Apollo Client

Let’s adapt the example from the GraphQL article by using the Apollo Client and instead a Web API application we are going to create a web site by cloning all of the structure, objects and content from the API project.

So now our Get() method in the ValuesController would return a View with the values model:

var values = client.GetValues();
return View(values);

We are going to create the View and inside it just render the data.
The important part here is that we need to import the Apollo client library like so:

<script src="https://unpkg.com/apollo-client-browser@1.9.0"></script>

Now let’s add a custom script file where we are going to create the Apollo client and write our query:

// Create the Apollo client
const apolloClient = new Apollo.lib.ApolloClient({
    networkInterface: Apollo.lib.createNetworkInterface({
        uri: 'https://localhost:<port>/graphql'

// The GraphQL query
const valuesQuerry = Apollo.gql'
query values 
          id name quantity description 

      query: valuesQuery
    }).then(result => {
      // Use the result.data object to consume the data from the server and render it in the view
        . . .

Finally include the newly created script in the view.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s