Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for GraphQL with dotnetcore
Arjun Shetty
Arjun Shetty

Posted on • Edited on

     

GraphQL with dotnetcore

What does GraphQL solve?

Overfetching, Underfetching, and reduced round trips. While using GraphQL we move the control of data over to API instead of the client-side. Also, GraphQL came to existence from the labs of Facebook while working on a mobile app.
These days servers have become so cheap it makes sense to move the control over to server instead of the client so the end-users consume the least amount of data also the processing power of his device.

Well, I must say this is kind of a genre which is created, there are scenarios where the other way is also true.

Writing a GraphQL with Dotnet core is as easy as this one.

Create a web API with default webapi template

dotnet new webapi -o graphql-sample

Add these two libraries, One is the GraphQL implementation and one more is to enable a cool library which makes testing and checking the API easier.

dotnet add package GraphQL

dotnet add package graphiql

Insert this line

app.UseGraphiQl("/graphql");

insideConfigure method inStartup.cs. Which says expose the cool UI to test GraphQL at/graphql endpoint.

Add a new classGraphQLQuery which will be used tomodel bind our through our controllers. In our first sample, we will just use the Query property of this model to retrieve the query to run on the server.

publicclassGraphQLQuery{publicstringOperationName{get;set;}publicstringNamedQuery{get;set;}publicstringQuery{get;set;}publicJObjectVariables{get;set;}}
Enter fullscreen modeExit fullscreen mode

Now let us add our domain objects for which we will use the hardcoded list of movies from IMDB.

publicclassMovie{publicstringTitle{get;set;}publicstringYear{get;set;}publicstringStars{get;set;}publicfloatRating{get;set;}publicstringGenre{get;set;}}
Enter fullscreen modeExit fullscreen mode

Like in C# we write models and methods in it to access the data, in GraphQL we use schemas to do the same.

Add this MovieSchema

publicclassMovieSchema{privateISchemaSchema{get;set;}publicISchemaGraphQLQuoteSchema{get{returnthis.Schema;}}publicMovieSchema(){this.Schema=GraphQL.Types.Schema.For(@"          type Movie {            title: String,            year: String,            stars: String,            rating: Float,            genre: String,          }          type Query {              movies: [Movie],              moviesByGenre(genre: String): [Movie],          }      ",_=>{_.Types.Include<Query>();});}}
Enter fullscreen modeExit fullscreen mode

If you look at the schema which is written string is the one which defines the GrahQL queries and the types used. We have defined 2 queriesmovies &moviesByGenre(genre: String). The first query returns all the movie types and the latter get movies filtered with the genre passed.

Now to make our API understand these queries we create this below classQuery

[GraphQLMetadata("movies")]publicIEnumerable<Movie>GetMovies(){returnmovies;}[GraphQLMetadata("moviesByGenre")]publicIEnumerable<Movie>GetQuoteByRegion(stringgenre){returnmovies.Where(q=>q.Genre==genre);}
Enter fullscreen modeExit fullscreen mode

The attributes that you see on the top of the methods is what maps these methods to the queries defined in the schema. Themovies is just a collection of data.

That is it!
When you run this project and browse the/graphql endpoint you would see theGraphiQL UI browse the API.

In the editor now enter the below query one by and see it for your self.

Query1

{moviesByGenre(genre:"Drama"){title,rating}}
Enter fullscreen modeExit fullscreen mode

Query2

{moviesByGenre(genre:"Drama"){title,rating}}
Enter fullscreen modeExit fullscreen mode

For the full source code checkout thisGitHub Repo.

Photo by Alina Grubnyak on Unsplash

Originally posted onBitsmonkey Blog

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

  • Joined

More fromArjun Shetty

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp