Getting started with GraphQL in .NET 6 - Part 1
Tags: graphql, dotnet, dotnet6, tutorial
Published: 2021-10-17 10:06:25

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](https://dotnet.microsoft.com/download/dotnet/6.0)
2. Your favorite IDE/editor. In my case, I will use [Visual Studio Code](https://code.visualstudio.com/) + [C# Extension](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csharp)

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](https://graphql.org/learn/).

## Project Preparation

* Create New Project

```bash
dotnet new webapi -o GraphQLNetExample
```

* Create a Solution

```bash
dotnet new sln
```

* Link solution to the project

```bash
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.

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

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

```csharp
namespace GraphQLNetExample.Notes;

public class Note
{
  public Guid Id { get; set; }
  public string Message { get; set; }
} 
```

* Create `NoteType.cs` in `GraphQLNetExample/Notes`. This class is the type definition for GraphQL.

```csharp
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.

```csharp
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.

```csharp
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 my `Program.cs`.

```csharp
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`

![Run Project](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g2c1kuiyteilr61jcoug.png)
 

* 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qoddsmt2jlc4uqgyimaj.png)
 
* Test our query. Please write this query.

```graphql
{
  notes {
    id,
    message
  }
}
```

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

![Query result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/grf3ckdan53m8sd13scw.png)

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

```graphql
{
  notes {
    message
  }
}
```

![Result message only](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xa18ujjsjtmf3t1lpdn9.png)

## Repository

{% github bervproject/GraphQLNetExample %}

## 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](https://media.giphy.com/media/3o6Zt6KHxJTbXCnSvu/giphy.gif)