- Notifications
You must be signed in to change notification settings - Fork137
A GraphQL Client for .NET Standard
License
graphql-dotnet/graphql-client
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
A GraphQL Client for .NET Standard over HTTP.
Provides the following packages:
The Library will try to follow the following standards and documents:
The intended use ofGraphQLHttpClient is to keep one instance alive per endpoint (obvious in case you'reoperating full websocket, but also true for regular requests) and is built with thread-safety in mind.
// To use NewtonsoftJsonSerializer, add a reference to// NuGet package GraphQL.Client.Serializer.NewtonsoftvargraphQLClient=newGraphQLHttpClient("https://api.example.com/graphql",newNewtonsoftJsonSerializer());
Note
GraphQLHttpClient is meant to be used as a single long-lived instance per endpoint (i.e. register as singleton in a DI system), which should be reused for multiple requests.
varheroRequest=newGraphQLRequest{Query=""" { hero { name } } """};
varpersonAndFilmsRequest=newGraphQLRequest{Query=""" query PersonAndFilms($id: ID) { person(id: $id) { name filmConnection { films { title } } } } """,OperationName="PersonAndFilms",Variables=new{id="cGVvcGxlOjE="}};
Warning
Be careful when usingbyte[] in your variables object, as most JSON serializers will treat that as binary data.
If you really need to send alist of bytes with abyte[] as a source, then convert it to aList<byte> first, which will tell the serializer to output a list of numbers instead of a base64-encoded string.
publicclassResponseType{publicPersonTypePerson{get;set;}}publicclassPersonType{publicstringName{get;set;}publicFilmConnectionTypeFilmConnection{get;set;}}publicclassFilmConnectionType{publicList<FilmContentType>Films{get;set;}}publicclassFilmContentType{publicstringTitle{get;set;}}vargraphQLResponse=awaitgraphQLClient.SendQueryAsync<ResponseType>(personAndFilmsRequest);varpersonName=graphQLResponse.Data.Person.Name;
Using the extension method for anonymously typed responses (namespaceGraphQL.Client.Abstractions) you could achieve the same result with the following code:
vargraphQLResponse=awaitgraphQLClient.SendQueryAsync(personAndFilmsRequest,()=>new{person=newPersonType()});varpersonName=graphQLResponse.Data.person.Name;
Important
Note that the field in the GraphQL response which gets deserialized into the response object is thedata field.
A common mistake is to try to directly use thePersonType class as response type (because thats thething you actually want to query), but the returned response object contains a propertyperson containing aPersonType object (like theResponseType modelled above).
publicclassUserJoinedSubscriptionResult{publicChatUserUserJoined{get;set;}publicclassChatUser{publicstringDisplayName{get;set;}publicstringId{get;set;}}}
varuserJoinedRequest=newGraphQLRequest{Query=@" subscription { userJoined{ displayName id } }"};IObservable<GraphQLResponse<UserJoinedSubscriptionResult>>subscriptionStream=client.CreateSubscriptionStream<UserJoinedSubscriptionResult>(userJoinedRequest);varsubscription=subscriptionStream.Subscribe(response=>{Console.WriteLine($"user '{response.Data.UserJoined.DisplayName}' joined")});
subscription.Dispose();
Automatic persisted queries (APQ) are supported since client version 6.1.0.
APQ can be enabled by configuringGraphQLHttpClientOptions.EnableAutomaticPersistedQueries to resolve totrue.
By default, the client will automatically disable APQ for the current session if the server responds with aPersistedQueryNotSupported error or a 400 or 600 HTTP status code.This can be customized by configuringGraphQLHttpClientOptions.DisableAPQ.
To re-enable APQ after it has been automatically disabled,GraphQLHttpClient needs to be disposed an recreated.
APQ works by first sending a hash of the query string to the server, and only sending the full query string if the server has not yet cached a query with a matching hash.With queries supplied as a string parameter toGraphQLRequest, the hash gets computed each time the request is sent.
When you want to reuse a query string (propably to leverage APQ 😉), declare the query using theGraphQLQuery class. This way, the hash gets computed once on constructionof theGraphQLQuery object and handed down to eachGraphQLRequest using the query.
GraphQLQueryquery=new(""" query PersonAndFilms($id: ID) { person(id: $id) { name filmConnection { films { title } } } } """);vargraphQLResponse=awaitgraphQLClient.SendQueryAsync<ResponseType>(query,"PersonAndFilms",new{id="cGVvcGxlOjE="});
.NET 7.0 introduced theStringSyntaxAttribute to have a unified way of telling what data is expected in a givenstring orReadOnlySpan<char>. IDEs like Visual Studio and Rider can then use this to provide syntax highlighting and checking.
From v6.0.4 on all GraphQL string parameters in this library are decorated with the[StringSyntax("GraphQL")] attribute.
Currently, there is no native support for GraphQL formatting and syntax highlighting in Visual Studio, but theGraphQLTools Extension provides that for you.
For Rider, JetBrains provides aPlugin, too.
To leverage syntax highlighting in variable declarations, use theGraphQLQuery class.
Blazor WebAssembly differs from other platforms as it does not support all features of other .NET runtime implementations. For instance, the following WebSocket options properties are not supported and will not be set:
About
A GraphQL Client for .NET Standard
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.