Hello, everyone! This is my first time to write series. I will write series about GraphQL example project in .NET 6. Please make sure you are already downloaded some tools. Here the lists,
- .NET 6
- Your favorite IDE/editor. In my case, I will use Visual Studio Code + C# Extension
In part 1, I will not use databases. I will use in-memory lists. If you have many questions about GraphQL, I suggest you to learn more about GraphQL here.
Project Preparation
- Create New Project
dotnet new webapi -o GraphQLNetExample
- Create a Solution
dotnet new sln
- Link solution to the project
dotnet sln add GraphQLNetExample
Install Dependencies
- Install GraphQL. Feel free to choose either use command line or just input these definitions to your
.csproj
file. This is my.csproj
definition.
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="GraphQL" Version="4.6.1" />
<PackageReference Include="GraphQL.MicrosoftDI" Version="4.6.1" />
<PackageReference Include="GraphQL.Server.Authorization.AspNetCore" Version="5.0.2" />
<PackageReference Include="GraphQL.Server.Transports.AspNetCore.SystemTextJson" Version="5.0.2" />
<PackageReference Include="GraphQL.Server.Ui.Altair" Version="5.0.2" />
<PackageReference Include="GraphQL.SystemTextJson" Version="4.6.1" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.1.5" />
</ItemGroup>
</Project>
Note: If you copy-paste the definition, don't forget to download the dependencies, you can use dotnet restore GraphQLNetExample
or dotnet restore
.
Coding Time
Create folder/directory under
GraphQLNetExample
with nameNotes
Create
Note.cs
inGraphQLNetExample/Notes
. This class is the model definition.
namespace GraphQLNetExample.Notes;
public class Note
{
public Guid Id { get; set; }
public string Message { get; set; }
}
- Create
NoteType.cs
inGraphQLNetExample/Notes
. This class is the type definition for GraphQL.
using GraphQL.Types;
namespace GraphQLNetExample.Notes;
public class NoteType : ObjectGraphType<Note>
{
public NoteType()
{
Name = "Note";
Description = "Note Type";
Field(d => d.Id, nullable: false).Description("Note Id");
Field(d => d.Message, nullable: true).Description("Note Message");
}
}
- Create the query for GraphQL. I write the code at
GraphQLNetExample/Notes/NotesQuery.cs
. This class is for you define your query definition. You need to define the resolver, in this case we just use in-memory list.
using GraphQL.Types;
namespace GraphQLNetExample.Notes;
public class NotesQuery : ObjectGraphType
{
public NotesQuery()
{
Field<ListGraphType<NoteType>>("notes", resolve: context => new List<Note> {
new Note { Id = Guid.NewGuid(), Message = "Hello World!" },
new Note { Id = Guid.NewGuid(), Message = "Hello World! How are you?" }
});
}
}
- Create the schema for our Notes. I write the code at
GraphQLNetExample/Notes/NotesSchema.cs
. I use this class to register my query and define my schema.
using GraphQL.Types;
namespace GraphQLNetExample.Notes;
public class NotesSchema : Schema
{
public NotesSchema(IServiceProvider serviceProvider) : base(serviceProvider)
{
Query = serviceProvider.GetRequiredService<NotesQuery>();
}
}
- Time to register our schema and setup the GraphQL. Please update your
Program.cs
. This is myProgram.cs
.
using GraphQL;
using GraphQL.MicrosoftDI;
using GraphQL.Server;
using GraphQL.SystemTextJson;
using GraphQL.Types;
using GraphQLNetExample.Notes;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// add notes schema
builder.Services.AddSingleton<ISchema, NotesSchema>(services => new NotesSchema(new SelfActivatingServiceProvider(services)));
// register graphQL
builder.Services.AddGraphQL(options =>
{
options.EnableMetrics = true;
})
.AddSystemTextJson();
// default setup
builder.Services.AddControllers();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new() { Title = "GraphQLNetExample", Version = "v1" });
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "GraphQLNetExample v1"));
// add altair UI to development only
app.UseGraphQLAltair();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
// make sure all our schemas registered to route
app.UseGraphQL<ISchema>();
app.Run();
Test our code
- Since I use Altair, so we can check our schemas at Altair. Please run your project first.
dotnet run --project GraphQLNetExample
- Please check your app URL. In my case, I use port 7298. So I can open my Altair use this link:
https://localhost:7298/ui/altair
. You can open the URL at browser and see the UI like this.
- Test our query. Please write this query.
{
notes {
id,
message
}
}
The result will be like this, please expect Id
will be different since we always generate that.
How about if you want message only? Yeah, that is handled by GraphQL. Change the query like this,
{
notes {
message
}
}
Repository
bervProject / GraphQLNETExample
Part of post: https://dev.to/berviantoleo/getting-started-graphql-in-net-6-part-1-4ic2
GraphQL .NET Example
GraphQL example implementation in .NET 8.
Notice
Part of this blog post
LICENSE
MIT
Yey
Easy, right? In this part, you are already learned about GraphQL and how to write GraphQL query in .NET 6. If you have some questions, please comment here. I really appreciate with all your suggestions and opinions.
Thank you for following this article until the end of this part. I will continue the next part maybe next week or next month. I really appreciate if you have other queries about my article. The next part is continuing this article and we will learn more about mutation
and connect the query
& mutation
to database. Stay tune.
Top comments (7)
Hi! Great article! Thank you. You can also setup the launchUrl to "ui/altair", under profiles/ section of the launchSettings.json to have the app start on the graphql page right away.
Hi,
The .AddGraphQL(..) extensions are marked as [Obsolete]. But they don't indicate what to use as an alternative.
Hi.
I've just checked their documentation. I think they have another method.
You can check in here.
github.com/graphql-dotnet/server#c...
Maybe I'll keep update with that. Thank you.
It works very well! Thanks!
Thank you for the updates. I'll try to find out about that.
Great article that got me on the way. Thank you!
Have you had the chance to implement GraphQL.NET V5 that seems to have some breaking changes?
I updated to V7 instead of V5 in this post.
dev.to/berviantoleo/updating-my-pr...
Feel free to give feedback in that post.