Overview:
Hello Developers,
In today’s world, we use lots of web and mobile applications, all of these applications require data. These data are provided by API like application request to API, API process those requests and give a response. This is a common way to fetch data from the server.
So why do we need GraphQL?
Let’s have a deeper look with an example
We have one application where we have lots of APIs like some API is for getting data from one table, some API is for getting data from another table. So there are multiple endpoints but in GraphQL, we only have one endpoint which is used for getting data from both tables
The second benefit of Graphql is when you required only 2 column data then GraphQL is only providing to you 2 column data if you required 3 column data then GraphQL provides you 3 columns with the same endpoint, but in REST API this is not possible
Introduction of GraphQL
It’s an object-relational database management system (ORDBMS), developed at the University of California at Berkeley Computer Science Department by Michael Stonebraker.
Its source code is available under PostgreSQL license, a liberal open-source license. Anyone with the proper abilities is free to use, modify, and distribute PostgreSQL in any form.
It helps a big part of the SQL standard and offers many modern features:
Myths about GraphQL
Is GraphQL related to Graph Database?
- No, GraphQL is not related to the graph database. It’s the same as javascript and java are compared. In GraphQL, graph means our query is now able to crawl in rest API and pickup the selective data and QL stand for the Query language
Should I stop using the REST API Now?
- No, because most applications working on the REST API and they are working fine on the REST API, GraphQL is used for large amounts of data, and many requests in a day
GraphQL with .Net
First of all, you need to create Asp.net Web API Core Project in Visual studio
So get the basic structure of the dot net core API project then you need to add some libraries to the project.
After this, we need to add EF library for database connectivity, in this example, we using Entity Framework.
So first of all we create 1 folder and the folder name is “Entities” and in this folder, we create 1 file Owner.cs
This is the code of this file.
public class Owner { [Key] public Guid Id { get; set; } [Required(ErrorMessage = "Name required")] public string Name { get; set; } public string Address { get; set; } }
Now we create a Repository Folder and In this folder, we create Another folder with the Interface name. In Interface folder we create IOwnerRepository.cs File.
public interface IOwnerRepository { IEnumerable<Owner> GetAll(); }
In this interface, we declare one method with “GetAll” Name.
So we implement this interface in another class and create a class in the same folder with the “OwnerRepository” name.
public class OwnerRepository : IOwnerRepository { private readonly ApplicationContext _context; public OwnerRepository(ApplicationContext context) { _context = context; SeedOwner(); } public IEnumerable<Owner> GetAll() => _context.Owners.ToList(); public void SeedOwner() { IList<Owner> owner = new List<Owner>(); owner.Add(new Owner() { Id = System.Guid.NewGuid(), Name = "Rajveer", Address = "Address1" }); owner.Add(new Owner() { Id = System.Guid.NewGuid(), Name = "utkarsh", Address = "Address1" }); owner.Add(new Owner() { Id = System.Guid.NewGuid(), Name = "Akshay", Address = "Address1" }); owner.Add(new Owner() { Id = System.Guid.NewGuid(), Name = "Mahesh", Address = "Address1" }); owner.Add(new Owner() { Id = System.Guid.NewGuid(), Name = "Kinjal", Address = "Address1" }); owner.Add(new Owner() { Id = System.Guid.NewGuid(), Name = "Divya", Address = "Address1" }); _context.Owners.AddRange(owner); _context.SaveChanges(); } }
In this class, we implemented the interface method and set ApplicationContext in Constructor, and also set some seed data in the constructor.
Now we need to setup ApplicationContext, So again we create a class with the “ApplicationContext” name.
public class ApplicationContext : DbContext { public ApplicationContext(DbContextOptions options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { } public DbSet<Owner> Owners { get; set; } }
In this class, we set DbSet which is the owner entity.
After creating repository classes, we need to configure our ApplicationContext in Startup Class.
services.AddDbContext<ApplicationContext>(opt =>opt.UseSqlServer("Your Connectionstring")); services.AddScoped<IOwnerRepository, OwnerRepository>();
So after this, we need to fire Some EF Command Like…
- Add-Migration <Migration Name>
- Update-database -Verbose
Before executing this command you need to install some NuGet packages From the NuGet Package Manager.
You can check DB is Created in the Database.
Now we set up GraphQL.
Before setting up GraphQL we need some NuGet Package.
So after installing this NuGet Package we create GraphQL Folder and in this folder, we create another 3 folders called
- GraphQLQueries
- GraphQLSchema
- GraphQLTypes
In GraphQLQueries Folder we create files for Defining Query for GraphQL.
In GraphQLSchema Folder we create files for Schema.
In GraphQLTypes Folder we create files for Type because GraphQL has its own types also.
First of all, we create an OwnerType file in GraphQLTypes Folder.
public class OwnerType : ObjectGraphType<Owner> { public OwnerType() { Field(x => x.Id, type: typeof(IdGraphType)).Description("Id property is of owner object."); Field(x => x.Name).Description("Name property is of owner object."); Field(x => x.Address).Description("Address property is of owner object."); } }
In this file, we define OwnerType for GraphQL and add fields for GraphQL and a description of those fields.
After that, We create Query files in GraphQLQueries and our file name is AppQuery. In this file, we define all queries.
public class AppQuery : ObjectGraphType { public AppQuery(IOwnerRepository repository) { Field<ListGraphType<OwnerType>> ( "owners", resolve: context => repository.GetAll() ); } }
In this file, we define the name of an object “owners” and resolve for this object So whenever we call owners then GraphQL returns all data of table because in resolve we call “GetAll” method which is used for getting all data from DB.
Now we define a schema in the GraphQLSchema folder, In this Folder, we create 1 file name of that file is “AppSchema”.
public class AppSchema: Schema { public AppSchema(IServiceProvider provider) : base(provider) { Query = provider.GetRequiredService<AppQuery>(); } }
Now our GraphQL structure is ready but we need to configure our GraphQL So again we go to our startup file and configure our GraphQL.
We need to define our Schema in the Startup file.
services.AddScoped<AppSchema>(); services.AddGraphQL().AddSystemTextJson().AddGraphTypes(typeof(AppSchema), ServiceLifetime.Scoped);
Also, add in IapplicatonBuilder.
app.UseGraphQL<AppSchema>(); app.UseGraphQLPlayground(options: new GraphQLPlaygroundOptions());
So we are ready to run our project. So hold your breath and press F5 or Run your Project.
So get this type of UI if you didn’t get this URL then don’t be panic just point to this URL <domainname>ui/playground
So now you write a query and get data.
Conclusion
So in this blog, we learn what is GraphQL, myths about GraphQL, how to setup Graph QL with .Net.