What is GraphQL?
- Yet another communication standard
- Mainly for client ⇔ server
- GraphQL is typically served over HTTP
- Contrary to REST we use a single endpoint
- GraphQL services typically respond using JSON (yet not required by the spec)
Data model
With GraphQL you think of data as a graph of nodes.
Query language
GraphQL has its own language to query data
Why?
- GraphQL gives power to the client.
- The client can specify what they want exactly for a specific use-case.
- The server needs to be implemented in a way that supports the queries.
- This leads to very targeted queries fetching only the information that is needed.
Add GraphQL to an ASP.NET Core Web API
Using HotChocolate1
NuGet:
Add a query
The methods can return any data. We just return an empty list here to get started.
Register with dependency injection
Run and verify
Run application and go to route /graphql in the browser.
Create a new document and try out the following query.
Should yield result:
Add connection to database
Verify again
returns
Get element by ID
Add GraphQL to a Blazor WASM Client
Using StrawberryShake2
Generate client
Customize namespace
Write query definition
Build project
Register client with dependency injection
Query data
Mutations
GraphQL Mutations let you modify data.
You send the data and have control of what you get back.
Server Implementation
It is recommended to create specific types for adding items (e.g. without ID property).
Registration
Update Client
Add Definition for Mutation
Build again
Use client to modify data
Subscriptions
GraphQL offers an easy way to subscribe to events.
The Server can notify the client of changes via a websocket connection.
Server Implementation
Send subscription message in Mutation
Registration
Test subscriptions
Client implementation
Add subscription definition
Build project to regenerate client afterwards.
Configuration
Use subscription in client