Sure! Below is a comprehensive example demonstrating how to set up a .NET 8 application using Entity Framework Core 8, Hot Chocolate GraphQL 13, and SQL Server to create and query an Items table with dynamic JSON data. This example includes:
- Project Setup
- Entity and DbContext Configuration
- Database Initialization and Seeding
- GraphQL Schema and Resolvers
- Filtering, Sorting, and Pagination on JSON Data
- Running the Application
Let's dive into each part step-by-step.
1. Project Setup
First, create a new ASP.NET Core Web API project.
dotnet new webapi -n GraphQLJsonExample
cd GraphQLJsonExample
Install the necessary NuGet packages:
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
dotnet add package HotChocolate.AspNetCore
dotnet add package HotChocolate.Data
dotnet add package HotChocolate.Data.Filters
dotnet add package HotChocolate.Data.Sorting
dotnet add package Microsoft.Extensions.Configuration
Ensure your .csproj file includes these packages.
2. Entity and DbContext Configuration
2.1. Creating the Item Entity
Create a new folder Models and add Item.cs:
// Models/Item.cs
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace GraphQLJsonExample.Models
{
public class Item
{
[Key]
public int Id { get; set; }
// Store JSON as string
[Required]
[Column(TypeName = "varchar(max)")]
public string Data { get; set; }
}
}
2.2. Configuring the AppDbContext
Create a new folder Data and add AppDbContext.cs:
// Data/AppDbContext.cs
using GraphQLJsonExample.Models;
using Microsoft.EntityFrameworkCore;
namespace GraphQLJsonExample.Data
{
public class AppDbContext : DbContext
{
public DbSet<Item> Items => Set<Item>();
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
// Optional: Configure model further if needed
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// Configure the Data column as varchar(max)
modelBuilder.Entity<Item>()
.Property(i => i.Data)
.HasColumnType("varchar(max)");
}
}
}
2.3. Configuring Connection String
In appsettings.json, add the connection string to your SQL Server:
// appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "Server=YOUR_SERVER_NAME;Database=GraphQLJsonDb;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
// ... existing logging configuration
},
"AllowedHosts": "*"
}
Replace YOUR_SERVER_NAME with your actual SQL Server instance name.
3. Database Initialization and Seeding
We'll use EF Core's EnsureCreated method for simplicity to create and seed the database. In a production scenario, consider using proper migrations.
3.1. Seeding Sample Data
Create a new class DbInitializer.cs in the Data folder:
// Data/DbInitializer.cs
using GraphQLJsonExample.Models;
using Microsoft.EntityFrameworkCore;
namespace GraphQLJsonExample.Data
{
public static class DbInitializer
{
public static void Initialize(AppDbContext context)
{
// Ensure database is created
context.Database.EnsureCreated();
// Check if any items exist
if (context.Items.Any())
{
return; // DB has been seeded
}
// Seed with sample data
var items = new List<Item>
{
new Item
{
Data = @"
{
""name"": ""Item 1"",
""price"": 10.99,
""category"": ""Books"",
""tags"": [""fiction"", ""bestseller""]
}"
},
new Item
{
Data = @"
{
""name"": ""Item 2"",
""price"": 5.49,
""category"": ""Stationery"",
""tags"": [""office"", ""supplies""]
}"
},
new Item
{
Data = @"
{
""name"": ""Item 3"",
""price"": 15.00,
""category"": ""Electronics"",
""tags"": [""gadgets"", ""new""]
}"
}
};
context.Items.AddRange(items);
context.SaveChanges();
}
}
}
3.2. Initializing the Database at Startup
Modify Program.cs to initialize the database during application startup.
// Program.cs
using GraphQLJsonExample.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Configure EF Core with SQL Server
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
// Add Hot Chocolate GraphQL services
builder.Services
.AddGraphQLServer()
.AddQueryType<Query>()
.AddFiltering()
.AddSorting();
var app = builder.Build();
// Initialize and seed the database
using (var scope = app.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
DbInitializer.Initialize(dbContext);
}
// Configure the HTTP request pipeline.
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGraphQL();
});
app.Run();
4. GraphQL Schema and Resolvers
4.1. Defining the GraphQL Item Type
Since the Data field contains dynamic JSON, we'll represent it as a Dictionary<string, object> in GraphQL. However, Hot Chocolate doesn't natively support Dictionary<string, object> as a JSON type, so we'll use a custom scalar for JSON.
First, install the HotChocolate.Data.Projections package if needed:
dotnet add package HotChocolate.Data.Projections
Now, create a custom scalar for JSON data.
4.1.1. Creating the JSON Scalar
Create a new folder GraphQL/Scalars and add JsonScalar.cs:
// GraphQL/Scalars/JsonScalar.cs
using HotChocolate.Language;
using HotChocolate.Types;
namespace GraphQLJsonExample.GraphQL.Scalars
{
public class JsonScalar : ScalarType<object, StringValueNode>
{
public JsonScalar() : base("Json")
{
}
public override IValueNode ParseResult(object resultValue)
{
if (resultValue is string s)
{
return new StringValueNode(s);
}
return base.ParseResult(resultValue);
}
public override IValueNode ParseValue(object value)
{
if (value is string s)
{
return new StringValueNode(s);
}
return base.ParseValue(value);
}
public override bool TryDeserialize(object resultValue, out object? value)
{
if (resultValue is string s)
{
value = s;
return true;
}
value = null;
return false;
}
public override bool TrySerialize(object? runtimeValue, out object? resultValue)
{
if (runtimeValue is string s)
{
resultValue = s;
return true;
}
resultValue = null;
return false;
}
}
}
4.1.2. Registering the JSON Scalar
Modify Program.cs to register the custom scalar:
// Program.cs
using GraphQLJsonExample.Data;
using GraphQLJsonExample.GraphQL;
using GraphQLJsonExample.GraphQL.Scalars;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Configure EF Core with SQL Server
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
// Add Hot Chocolate GraphQL services
builder.Services
.AddGraphQLServer()
.AddQueryType<Query>()
.AddFiltering()
.AddSorting()
.AddType<JsonScalar>(); // Register the custom JSON scalar
var app = builder.Build();
// Initialize and seed the database
using (var scope = app.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
DbInitializer.Initialize(dbContext);
}
// Configure the HTTP request pipeline.
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGraphQL();
});
app.Run();
4.2. Defining the GraphQL Query
Create a new folder GraphQL and add Query.cs:
// GraphQL/Query.cs
using GraphQLJsonExample.Data;
using GraphQLJsonExample.Models;
using HotChocolate;
using HotChocolate.Data;
using Microsoft.EntityFrameworkCore;
using System.Text.Json;
namespace GraphQLJsonExample.GraphQL
{
public class Query
{
// Basic field to get items with filtering, sorting, and pagination
[UseDbContext(typeof(AppDbContext))]
[UsePaging(IncludeTotalCount = true)]
[UseFiltering]
[UseSorting]
public IQueryable<Item> GetItems([ScopedService] AppDbContext context)
{
return context.Items;
}
// Advanced fields to filter/sort based on JSON data can be added here
}
}
4.3. Enabling Filtering and Sorting on JSON Fields
To filter and sort based on JSON fields, we'll use EF Core's JsonValue function to extract values from the JSON stored in the Data column.
We'll create a ItemFilter and ItemSortType to handle dynamic filtering and sorting.
4.3.1. Extending the Item Entity
To facilitate extracting JSON fields, add computed properties or methods in the Item class. However, since the JSON structure is dynamic, we'll handle this directly in the GraphQL layer.
4.3.2. Creating Dynamic Filters and Sorters
Instead of creating fixed filters and sorters, we'll use Hot Chocolate's filtering and sorting capabilities with custom resolvers.
Modify the Query.cs to include filtering and sorting based on JSON fields. Here's an example where you can filter by name and sort by price extracted from the JSON Data.
// GraphQL/Query.cs
using GraphQLJsonExample.Data;
using GraphQLJsonExample.Models;
using HotChocolate;
using HotChocolate.Data;
using Microsoft.EntityFrameworkCore;
using System.Text.Json;
namespace GraphQLJsonExample.GraphQL
{
public class Query
{
// Basic field to get items with filtering, sorting, and pagination
[UseDbContext(typeof(AppDbContext))]
[UsePaging(IncludeTotalCount = true)]
[UseFiltering]
[UseSorting]
public IQueryable<Item> GetItems([ScopedService] AppDbContext context)
{
return context.Items;
}
// Example of filtering by JSON "name" field
[UseDbContext(typeof(AppDbContext))]
[UsePaging(IncludeTotalCount = true)]
[UseFiltering]
[UseSorting]
public IQueryable<ItemDto> GetItemsWithJsonFields([ScopedService] AppDbContext context)
{
return context.Items.Select(item => new ItemDto
{
Id = item.Id,
Name = EF.Functions.JsonValue(item.Data, "$.name"),
Price = EF.Functions.JsonValue(item.Data, "$.price") != null ?
double.Parse(EF.Functions.JsonValue(item.Data, "$.price")) : 0,
Category = EF.Functions.JsonValue(item.Data, "$.category"),
Tags = EF.Functions.JsonValue(item.Data, "$.tags") // You may need to process this further
});
}
}
// Data Transfer Object for querying JSON fields
public class ItemDto
{
public int Id { get; set; }
public string? Name { get; set; }
public double Price { get; set; }
public string? Category { get; set; }
public string? Tags { get; set; }
}
}
4.3.3. Defining ItemDto in GraphQL
Now, define ItemDto in GraphQL to expose the JSON fields.
Create ItemDtoType.cs in GraphQL/Types:
// GraphQL/Types/ItemDtoType.cs
using HotChocolate.Types;
namespace GraphQLJsonExample.GraphQL.Types
{
public class ItemDtoType : ObjectType<ItemDto>
{
protected override void Configure(IObjectTypeDescriptor<ItemDto> descriptor)
{
descriptor.Field(f => f.Id).Type<NonNullType<IdType>>();
descriptor.Field(f => f.Name).Type<StringType>();
descriptor.Field(f => f.Price).Type<FloatType>();
descriptor.Field(f => f.Category).Type<StringType>();
descriptor.Field(f => f.Tags).Type<StringType>(); // Consider parsing JSON array if needed
}
}
}
Register ItemDtoType in Program.cs:
// Program.cs
using GraphQLJsonExample.Data;
using GraphQLJsonExample.GraphQL;
using GraphQLJsonExample.GraphQL.Scalars;
using GraphQLJsonExample.GraphQL.Types;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Configure EF Core with SQL Server
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
// Add Hot Chocolate GraphQL services
builder.Services
.AddGraphQLServer()
.AddQueryType<Query>()
.AddType<ItemDtoType>() // Register ItemDtoType
.AddFiltering()
.AddSorting()
.AddType<JsonScalar>(); // Register the custom JSON scalar
var app = builder.Build();
// Initialize and seed the database
using (var scope = app.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
DbInitializer.Initialize(dbContext);
}
// Configure the HTTP request pipeline.
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGraphQL();
});
app.Run();
4.4. Finalizing the GraphQL Schema
Ensure the ItemDtoType is correctly integrated and that the queries support filtering, sorting, and pagination.
5. Filtering, Sorting, and Pagination on JSON Data
5.1. Using ItemDto for Queries
With the ItemDto projection, you can filter and sort based on the fields extracted from the JSON Data column.
Example GraphQL Queries:
- Query with Filtering by Name and Category, Sorting by Price, and Pagination
query {
itemsWithJsonFields(
where: {
name: { eq: "Item 1" },
category: { eq: "Books" }
},
order: { price: ASC },
first: 10
) {
nodes {
id
name
price
category
tags
}
totalCount
pageInfo {
hasNextPage
hasPreviousPage
}
}
}
- Query with Price Greater Than a Value
query {
itemsWithJsonFields(
where: {
price: { gt: 10 }
},
order: { price: DESC },
first: 5
) {
nodes {
id
name
price
category
tags
}
totalCount
pageInfo {
hasNextPage
hasPreviousPage
}
}
}
5.2. Notes on JSON Array Fields
The tags field is stored as a JSON array. In the ItemDto, it's currently represented as a string. For better functionality:
- Parse the JSON array into a list in
ItemDto.
- Update the GraphQL schema to expose it as a list.
Modify ItemDto and ItemDtoType:
// Query.cs
public class ItemDto
{
public int Id { get; set; }
public string? Name { get; set; }
public double Price { get; set; }
public string? Category { get; set; }
public List<string>? Tags { get; set; }
}
Update the projection to parse the JSON array:
public IQueryable<ItemDto> GetItemsWithJsonFields([ScopedService] AppDbContext context)
{
return context.Items.Select(item => new ItemDto
{
Id = item.Id,
Name = EF.Functions.JsonValue(item.Data, "$.name"),
Price = EF.Functions.JsonValue(item.Data, "$.price") != null ?
double.Parse(EF.Functions.JsonValue(item.Data, "$.price")) : 0,
Category = EF.Functions.JsonValue(item.Data, "$.category"),
Tags = EF.Functions.JsonValue(item.Data, "$.tags") != null ?
JsonSerializer.Deserialize<List<string>>(EF.Functions.JsonValue(item.Data, "$.tags"))
: new List<string>()
});
}
Update ItemDtoType:
// GraphQL/Types/ItemDtoType.cs
using HotChocolate.Types;
namespace GraphQLJsonExample.GraphQL.Types
{
public class ItemDtoType : ObjectType<ItemDto>
{
protected override void Configure(IObjectTypeDescriptor<ItemDto> descriptor)
{
descriptor.Field(f => f.Id).Type<NonNullType<IdType>>();
descriptor.Field(f => f.Name).Type<StringType>();
descriptor.Field(f => f.Price).Type<FloatType>();
descriptor.Field(f => f.Category).Type<StringType>();
descriptor.Field(f => f.Tags).Type<ListType<StringType>>(); // Now a list
}
}
}
Now, you can filter based on list contents if needed, but note that Hot Chocolate's default filtering might not support it directly.
5.3. Advanced Filtering
For more advanced scenarios, such as filtering within nested JSON or array elements, consider implementing custom filter operations or using raw SQL queries. However, this often adds complexity and may require careful handling to prevent SQL injection.
6. Running the Application
6.1. Applying Migrations (Optional)
If you prefer using migrations instead of EnsureCreated, you can set up migrations:
dotnet ef migrations add InitialCreate
dotnet ef database update
Ensure Microsoft.EntityFrameworkCore.Tools is installed.
6.2. Running the Application
Execute the application:
dotnet run
Open your browser and navigate to https://localhost:5001/graphql (URL may vary). You can use the GraphQL Playground or Banana Cake Pop to interact with your GraphQL API.
6.3. Sample GraphQL Query
Here's a sample query to retrieve items with pagination, filtering by category, and sorting by price:
query {
itemsWithJsonFields(
where: { category: { eq: "Books" } },
order: { price: DESC },
first: 2
) {
nodes {
id
name
price
category
tags
}
totalCount
pageInfo {
hasNextPage
hasPreviousPage
endCursor
startCursor
}
}
}
Expected Response:
{
"data": {
"itemsWithJsonFields": {
"nodes": [
{
"id": 1,
"name": "Item 1",
"price": 10.99,
"category": "Books",
"tags": ["fiction", "bestseller"]
}
// ... other items
],
"totalCount": 1,
"pageInfo": {
"hasNextPage": false,
"hasPreviousPage": false,
"endCursor": "YXJyYXljb25uZWN0aW9uOjE=",
"startCursor": "YXJyYXljb25uZWN0aW9uOjE="
}
}
}
}
Complete Code Listing
For reference, here's the complete code structure:
6.1. Models/Item.cs
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace GraphQLJsonExample.Models
{
public class Item
{
[Key]
public int Id { get; set; }
// Store JSON as string
[Required]
[Column(TypeName = "varchar(max)")]
public string Data { get; set; }
}
}
6.2. Data/AppDbContext.cs
using GraphQLJsonExample.Models;
using Microsoft.EntityFrameworkCore;
namespace GraphQLJsonExample.Data
{
public class AppDbContext : DbContext
{
public DbSet<Item> Items => Set<Item>();
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
// Optional: Configure model further if needed
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// Configure the Data column as varchar(max)
modelBuilder.Entity<Item>()
.Property(i => i.Data)
.HasColumnType("varchar(max)");
}
}
}
6.3. Data/DbInitializer.cs
using GraphQLJsonExample.Models;
using Microsoft.EntityFrameworkCore;
namespace GraphQLJsonExample.Data
{
public static class DbInitializer
{
public static void Initialize(AppDbContext context)
{
// Ensure database is created
context.Database.EnsureCreated();
// Check if any items exist
if (context.Items.Any())
{
return; // DB has been seeded
}
// Seed with sample data
var items = new List<Item>
{
new Item
{
Data = @"
{
""name"": ""Item 1"",
""price"": 10.99,
""category"": ""Books"",
""tags"": [""fiction"", ""bestseller""]
}"
},
new Item
{
Data = @"
{
""name"": ""Item 2"",
""price"": 5.49,
""category"": ""Stationery"",
""tags"": [""office"", ""supplies""]
}"
},
new Item
{
Data = @"
{
""name"": ""Item 3"",
""price"": 15.00,
""category"": ""Electronics"",
""tags"": [""gadgets"", ""new""]
}"
}
};
context.Items.AddRange(items);
context.SaveChanges();
}
}
}
6.4. GraphQL/Scalars/JsonScalar.cs
using HotChocolate.Language;
using HotChocolate.Types;
namespace GraphQLJsonExample.GraphQL.Scalars
{
public class JsonScalar : ScalarType<object, StringValueNode>
{
public JsonScalar() : base("Json")
{
}
public override IValueNode ParseResult(object resultValue)
{
if (resultValue is string s)
{
return new StringValueNode(s);
}
return base.ParseResult(resultValue);
}
public override IValueNode ParseValue(object value)
{
if (value is string s)
{
return new StringValueNode(s);
}
return base.ParseValue(value);
}
public override bool TryDeserialize(object resultValue, out object? value)
{
if (resultValue is string s)
{
value = s;
return true;
}
value = null;
return false;
}
public override bool TrySerialize(object? runtimeValue, out object? resultValue)
{
if (runtimeValue is string s)
{
resultValue = s;
return true;
}
resultValue = null;
return false;
}
}
}
6.5. GraphQL/Types/ItemDtoType.cs
using HotChocolate.Types;
namespace GraphQLJsonExample.GraphQL.Types
{
public class ItemDtoType : ObjectType<ItemDto>
{
protected override void Configure(IObjectTypeDescriptor<ItemDto> descriptor)
{
descriptor.Field(f => f.Id).Type<NonNullType<IdType>>();
descriptor.Field(f => f.Name).Type<StringType>();
descriptor.Field(f => f.Price).Type<FloatType>();
descriptor.Field(f => f.Category).Type<StringType>();
descriptor.Field(f => f.Tags).Type<ListType<StringType>>(); // Now a list
}
}
}
6.6. GraphQL/Query.cs
using GraphQLJsonExample.Data;
using GraphQLJsonExample.Models;
using HotChocolate;
using HotChocolate.Data;
using Microsoft.EntityFrameworkCore;
using System.Text.Json;
namespace GraphQLJsonExample.GraphQL
{
public class Query
{
// Basic field to get items with filtering, sorting, and pagination
[UseDbContext(typeof(AppDbContext))]
[UsePaging(IncludeTotalCount = true)]
[UseFiltering]
[UseSorting]
public IQueryable<Item> GetItems([ScopedService] AppDbContext context)
{
return context.Items;
}
// Example of filtering by JSON fields
[UseDbContext(typeof(AppDbContext))]
[UsePaging(IncludeTotalCount = true)]
[UseFiltering]
[UseSorting]
public IQueryable<ItemDto> GetItemsWithJsonFields([ScopedService] AppDbContext context)
{
return context.Items.Select(item => new ItemDto
{
Id = item.Id,
Name = EF.Functions.JsonValue(item.Data, "$.name"),
Price = EF.Functions.JsonValue(item.Data, "$.price") != null ?
double.Parse(EF.Functions.JsonValue(item.Data, "$.price")) : 0,
Category = EF.Functions.JsonValue(item.Data, "$.category"),
Tags = EF.Functions.JsonValue(item.Data, "$.tags") != null ?
JsonSerializer.Deserialize<List<string>>(EF.Functions.JsonValue(item.Data, "$.tags"))
: new List<string>()
});
}
}
// Data Transfer Object for querying JSON fields
public class ItemDto
{
public int Id { get; set; }
public string? Name { get; set; }
public double Price { get; set; }
public string? Category { get; set; }
public List<string>? Tags { get; set; }
}
}
6.7. Program.cs
using GraphQLJsonExample.Data;
using GraphQLJsonExample.GraphQL;
using GraphQLJsonExample.GraphQL.Scalars;
using GraphQLJsonExample.GraphQL.Types;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Configure EF Core with SQL Server
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
// Add Hot Chocolate GraphQL services
builder.Services
.AddGraphQLServer()
.AddQueryType<Query>()
.AddType<ItemDtoType>() // Register ItemDtoType
.AddFiltering()
.AddSorting()
.AddType<JsonScalar>(); // Register the custom JSON scalar
var app = builder.Build();
// Initialize and seed the database
using (var scope = app.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
DbInitializer.Initialize(dbContext);
}
// Configure the HTTP request pipeline.
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGraphQL();
});
app.Run();
Conclusion
This example demonstrates how to integrate Entity Framework Core with dynamic JSON data stored in a SQL Server varchar(max) column and expose it via a GraphQL API using Hot Chocolate. It includes:
- Creating and seeding the database with JSON data.
- Defining GraphQL types and queries that allow filtering, sorting, and pagination based on JSON fields.
Considerations for Production:
- Error Handling: Implement robust error handling, especially when parsing JSON.
- Performance: Querying JSON fields can be less efficient. Ensure proper indexing and consider caching strategies.
- Security: Validate and sanitize inputs to prevent SQL injection, especially when dealing with dynamic queries.
This setup provides a flexible foundation for working with dynamic JSON data in a modern .NET GraphQL API.