Blog

Filter posts by Category Or Tag of the Blog section!

GraphQL as an alternative for Rest

Friday, 02 November 2018

GraphQL is an open-source runtime for filling data query language introduced by Facebook. It could be an alternative to REST as it allows the client to define the structure of the data query based on the need and retrieve the same structure of the data from the server! Wow.. That's not all the story, in fact, the APIs of GraphQL get all the needed data in a single request while, traditional REST APIs sometimes require multiple URLs to fetch data. So it would be more efficient. Many programming languages support GraphQL, you can see the list of languages and frameworks here. I'm starting with C# and Dot Net. To keep it simple, create a console application and reference the GraphQL:

 

 

After installing, add a Class named Book in the project:

 

   class Book
    {
        public int Id { get; set; }

        public string Name { get; set; }
    }

 

Now, in order to use the above class as GraphQL metadata, there is an attribute with the same name in GraphQL namespace:

 

 class Query
    {
        [GraphQLMetadata("Book")]
        public Book Retrieve()
        {
            var book = new Book { Id = 1, Name = "Asp.net Core" };
            return book;
        }
    }

 

A simple method with a custom return type(Book) which has been assigned by GraphQLMetadata attribute. Now in order to retrieve the sample data via GraphQL as JSON, create a class and use the Schema class of QraphQL which lives in GraphQL.Types namespace:

 

 static class GraphQLRequest
    {
        public static string Request()
        {
            var schema = Schema.For(@"
                  type Book {
                    id: ID
                    name: String
                  }

                  type Query {
                    book: Book
                  }
                  ", q =>
                     {
                         q.Types.Include<Query>();
                     });

            var json = schema.Execute(q =>
            {
                q.Query = "{ book { id name } }";
            });

            return json;
        }
    }

 

Now if you call the above Request method in your program class:

 

 class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("{0}", GraphQLRequest.Request());
        }
    }

 

You will see the output of QraphQL as JSON:

 

comments powered by Disqus