Build an ASP.NET Core API (manual GraphQL client)
Learn how to build an ASP.NET Core Web API that retrieves content from Optimizely Graph using a lightweight manual GraphQL client.
This guide demonstrates how to build a simple ASP.NET Core Web API that connects to Optimizely Graph, queries content using GraphQL, and exposes it through REST endpoints.
This approach uses a manual GraphQL client. This approach works well for
- Small or experimental projects.
- Learning GraphQL requests and responses.
- Scenarios where you want full control over queries and models.
If you want automatic code generation, strong typing, and compile-time validation, see Build an ASP.NET Core API with StrawberryShake instead.
Create an ASP.NET Core project
Create a Web API project.
dotnet new webapi -n MyOptimizelyApp
cd MyOptimizelyAppInstall dependencies
Install the GraphQL HTTP client packages.
dotnet add package GraphQL.Client
dotnet add package GraphQL.Client.Serializer.Newtonsoft
dotnet add package Microsoft.Extensions.Options.ConfigurationExtensionsCreate GraphQL schema and queries
Download the schema and create queries based on the Alloy template.
# Download schema
dotnet graphql download https://cg.optimizely.com/content/v2?auth=3JCcia5gTU2RTiOv2aUCXu1ktYJjqzGgjXh2AVMFvxPyhJOY -f schema.graphqlUse the following query to retrieve a list of articles from the database:
query GetArticles($limit: Int = 10, $skip: Int = 0) {
ArticlePage(
orderBy: { _modified: DESC }
limit: $limit
skip: $skip
) {
items {
ContentLink {
Id
}
Name
RelativePath
TeaserText
PageImage {
Url
}
MainBody
}
total
}
}
query GetArticleById($id: String!) {
ArticlePage(
where: { ContentLink: { Id: { eq: $id } } }
) {
items {
ContentLink {
Id
}
Name
RelativePath
TeaserText
PageImage {
Url
}
MainBody
_modified
}
}
}
Configure GraphQL client
Create a .graphqlrc.json configuration file.
{
"schema": "schema.graphql",
"documents": "Queries/**/*.graphql",
"extensions": {
"strawberryShake": {
"name": "OptimizelyGraphClient",
"namespace": "MyOptimizelyApp.GraphQL",
"url": "https://cg.optimizely.com/content/v2?auth=YOUR_KEY"
}
}
}Register the GraphQL client in Program.cs.
using GraphQL.Client.Http;
using GraphQL.Client.Serializer.Newtonsoft;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<GraphQLHttpClient>(provider =>
{
return new GraphQLHttpClient(
"https://cg.optimizely.com/content/v2?auth=YOUR_KEY",
new NewtonsoftJsonSerializer()
);
});
builder.Services.AddControllers();
var app = builder.Build();
app.UseRouting();
app.MapControllers();
app.Run();Store endpoint in configuration (optional)
Add the endpoint to appsettings.json.
{
"OptimizelyGraph": {
"Endpoint": "https://cg.optimizely.com/content/v2?auth=YOUR_KEY"
}
}Create model
Create a model that matches your GraphQL response.
public class Article
{
public ContentLink ContentLink { get; set; }
public string Name { get; set; }
public string RelativePath { get; set; }
public string TeaserText { get; set; }
public MediaReference PageImage { get; set; }
public string MainBody { get; set; }
}
public class ContentLink { public string Id { get; set; } }
public class MediaReference { public string Url { get; set; } }
public class ContentResponse
{
public List<Article> Items { get; set; } = new();
public int Total { get; set; }
}
public class GraphQLResponse<T>
{
public T ArticlePage { get; set; }
}Create a controller
Create an ASP.NET Core controller that sends GraphQL queries to Optimizely Graph using the manual client and returns the results through REST API endpoints.
Create Controllers/ArticlesController.cs.
using GraphQL;
using GraphQL.Client.Http;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class ArticlesController : ControllerBase
{
private readonly GraphQLHttpClient _graphQLClient;
public ArticlesController(GraphQLHttpClient graphQLClient)
{
_graphQLClient = graphQLClient;
}
[HttpGet]
public async Task<ActionResult> GetArticles()
{
var query = @"
query {
ArticlePage(orderBy: { _modified: DESC }, limit: 10) {
items {
ContentLink { Id }
Name
RelativePath
TeaserText
PageImage { Url }
MainBody
}
total
}
}";
var request = new GraphQLRequest { Query = query };
var response =
await _graphQLClient.SendQueryAsync<GraphQLResponse<ContentResponse>>(request);
if (response.Errors?.Any() == true)
{
return BadRequest(response.Errors);
}
return Ok(response.Data.ArticlePage);
}
}Run and test the API
Run the application and verify that your API endpoint retrieves content from Optimizely Graph.
dotnet build
dotnet runTest the API endpoint
Use the https://localhost:7000/api/articles endpoint to test your API and confirm it returns content from Optimizely Graph.
Updated about 2 hours ago
