DEV Community

Cover image for Getting started with GraphQL in .NET 6 - Part 1
Bervianto Leo Pratama
Bervianto Leo Pratama

Posted on

Getting started with GraphQL in .NET 6 - Part 1

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,

  1. .NET 6
  2. 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
Enter fullscreen mode Exit fullscreen mode
  • Create a Solution
dotnet new sln
Enter fullscreen mode Exit fullscreen mode
  • Link solution to the project
dotnet sln add GraphQLNetExample
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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 name Notes

  • Create Note.cs in GraphQLNetExample/Notes. This class is the model definition.

namespace GraphQLNetExample.Notes;

public class Note
{
  public Guid Id { get; set; }
  public string Message { get; set; }
} 
Enter fullscreen mode Exit fullscreen mode
  • Create NoteType.cs in GraphQLNetExample/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");
  }
}
Enter fullscreen mode Exit fullscreen mode
  • 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?" }
    });
  }
}
Enter fullscreen mode Exit fullscreen mode
  • 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>();
  }
}
Enter fullscreen mode Exit fullscreen mode
  • Time to register our schema and setup the GraphQL. Please update your Program.cs. This is my Program.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();
Enter fullscreen mode Exit fullscreen mode

Test our code

  • Since I use Altair, so we can check our schemas at Altair. Please run your project first. dotnet run --project GraphQLNetExample

Run Project

  • 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.

Altair

  • Test our query. Please write this query.
{
  notes {
    id,
    message
  }
}
Enter fullscreen mode Exit fullscreen mode

The result will be like this, please expect Id will be different since we always generate that.

Query result

How about if you want message only? Yeah, that is handled by GraphQL. Change the query like this,

{
  notes {
    message
  }
}
Enter fullscreen mode Exit fullscreen mode

Result message only

Repository

GraphQL .NET Example

GraphQL example implementation in .NET 6.

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.

Thank you

Discussion (0)