<aside> 📚 📁 Category: Backend Development
</aside>
GraphQL is a query language for APIs and a runtime for executing those queries with your existing data. Developed by Facebook, it provides a complete and understandable description of the data in your API.
// Install: dotnet add package HotChocolate.AspNetCore
// Model
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
// Query Type
public class Query
{
public User GetUser(int id, [Service] IUserRepository repository)
{
return repository.GetUserById(id);
}
public IEnumerable<User> GetUsers([Service] IUserRepository repository)
{
return repository.GetAllUsers();
}
}
// Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddGraphQLServer()
.AddQueryType<Query>();
var app = builder.Build();
app.MapGraphQL();
app.Run();
# Get specific fields
{
user(id: 1) {
name
email
}
}
# With aliases and fragments
{
firstUser: user(id: 1) {
...userFields
}
secondUser: user(id: 2) {
...userFields
}
}
fragment userFields on User {
id
name
email
}