How to create a Graph QL API on Azure Functions

REST APIs are great, but they can result in either your application making an excessive number of requests to multiple endpoints, then only using a small percentage of the data returned. Or you end up making a large number of endpoints for specific purposes and now have maintenance hell to deal with.

If that's your situation then one option is to look at replacing some of that functionality with a Graph QL API. I'm not going to dig into what Graph QL APIs are (that's been covered by many people before me), but what I will do is show you how to make one in an Azure Function.

Your starting point is to use Hot Chocolate by Chilli Cream, not only does it have a fun meaningless name, but it also offers some great simple-to-use functionality. However, despite stating it works with Azure Functions, the documentation is all for ASP.NET Core, which is not the same thing.

Another issue I have with the documentation is that it doesn't explain particularly well how you configure it to work with a data access layer. Examples either have methods that return a dataset containing all related data, or they use Entity Framework, which as you generally wouldn't use your DB schema as an API schema feels like cheating.

So here is my guide from file new project to a working Graph QL API in an Azure Function.

File New Project

Starting right at the beginning, open Visual Studio and create a new Azure Function. For this demo, I'm using .NET 6 as that's the latest at the time of writing, and am going to create an HTTP trigger.

Create new Azure Function screen

For a data source, I've created a hard-coded repository containing Schools, Classes, and Students. Schools contain multiple classes and classes contain multiple students. Each repository contains functions to get all, get by id or get by the thing it's related to. e.g. Get Students by Class. Here's my code for it.

using AzureFunctionWithGraphApi.Models;
using System.Collections.Generic;
using System.Linq;

namespace AzureFunctionWithGraphApi.DataAccess
{
  public interface ISchoolRepository
  {
      List<School> All();
      School GetById(int id);
  }

  public interface IClassRepository
  {
      List<Class> All();
      Class GetById(int id);
      List<Class> GetBySchool(int schoolId);
  }

  public interface IStudentRepository {
      List<Student> All();
      Student GetById(int id);
      List<Student> GetByClass(int classId);
  }

  public static class DemoData
  {
      public static List<School> Schools = new List<School>()
      {
          new School() {Id = 1, Name = "Foo School"},
          new School() {Id = 2 , Name = "Boo School"},
      };

      public static List<Class> ClassList = new List<Class>()
      {
          new Class() {Id = 3, SchoolId = 1, Name = "Red Class", YearGroup = 1},
          new Class() {Id = 4, SchoolId = 1, Name = "Blue Class", YearGroup = 2},
          new Class() {Id =5, SchoolId = 2, Name = "Yellow Class", YearGroup = 1},
          new Class(){Id = 6, SchoolId = 2, Name = "Green Class", YearGroup = 2}
      };

      public static List<Student> Students = new List<Student>()
      {
          new Student() {Id = 1, ClassId = 3, FirstName = "John", Surname = "Smith"},
          new Student() {Id = 2, ClassId = 3, FirstName = "Sam", Surname = "Smith"},
          new Student() {Id = 3, ClassId = 4, FirstName = "Eric", Surname = "Smith"},
          new Student() {Id = 4, ClassId = 4, FirstName = "Rachel", Surname = "Smith"},
          new Student() {Id = 5, ClassId = 5, FirstName = "Tom", Surname = "Smith"},
          new Student() {Id = 6, ClassId = 5, FirstName = "Sally", Surname = "Smith"},
          new Student() {Id = 7, ClassId = 6, FirstName = "Sharon", Surname = "Smith"},
          new Student() {Id = 8, ClassId = 6, FirstName = "Kate", Surname = "Smith"}
      };
  }

  public class SchoolRepository : ISchoolRepository
  {
      public List<School> All()
      {
          return DemoData.Schools;
      }

      public School GetById(int id)
      {
          return DemoData.Schools.Where(x => x.Id == id).FirstOrDefault(); 
      }
  }

  public class ClassRepository : IClassRepository
  {
      public List<Class> All()
      {
          return DemoData.ClassList;
      }

      public Class GetById(int id)
      {
          return DemoData.ClassList.Where(x => x.Id == id).FirstOrDefault();
      }

      public List<Class> GetBySchool(int schoolId)
      {
          return DemoData.ClassList.Where((x) => x.SchoolId == schoolId).ToList();
      }
  }

  public class StudentRepository : IStudentRepository
  {
      public List<Student> All()
      {
          return DemoData.Students;
      }

      public List<Student> GetByClass(int classId)
      {
          return DemoData.Students.Where((x) => x.ClassId == classId).ToList();
      }

      public Student GetById(int id)
      {
          return DemoData.Students.Where(x => x.Id == id).FirstOrDefault();
      }
  }
}

If you want to use it, you'll also need the related models.

public class School
  {
      public int Id { get; set; }
      public string Name { get; set; }
  }

public class Class
  {
      public int Id { get; set; }
      public int SchoolId { get; set; }
      public int YearGroup { get; set; }
      public string Name { get; set; }
  }

public class Student
  {
      public int Id { get; set; }
      public int ClassId { get; set; }
      public string FirstName { get; set; }
      public string Surname { get; set; }
  }

Create a Graph QL API

With our project and data access layer created, lets get on with how to create a Graph QL in a .NET Azure Function.

Hot chocolate will provide all the functionality and can be added to your solution via Nuget. Just search for Hot Chocolate and make sure you pick the Azure Function version.

Hot Chocolate NuGet package

The HTTP Endpoint we created when creating the function needs updating to provide the route for the graph API.

using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using HotChocolate.AzureFunctions;

namespace AzureFunctionWithGraphApi
{
  public class GraphQlApi
  {
      [FunctionName("HttpExample")]
      public async Task<IActionResult> Run(
      [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "graphql/{**slug}")] HttpRequest req,
      [GraphQL] IGraphQLRequestExecutor executor,
      ILogger log)
      {
          log.LogInformation("C# HTTP trigger function processed a request.");

          return await executor.ExecuteAsync(req);
      }
  }
}

Next we need to configure what queries can be performed on the graph. For my example, I'm replicating the Get All and Get By Id methods from my data access layer.

One thing to note here is although I'm using dependency injection for my repositories they are using resolver injection on the methods rather than constructor injection. You can read more about why this is on the Chilli Cream site here, but essentially constructor injector won't work.

using AzureFunctionWithGraphApi.DataAccess;
using AzureFunctionWithGraphApi.Models;
using HotChocolate;
using System.Collections.Generic;

namespace AzureFunctionWithGraphApi
{
  public class Query
  {
      public List<School> GetSchools([Service] ISchoolRepository schoolRepository)
      {
          return schoolRepository.All();
      }
      public School GetSchoolById([Service] ISchoolRepository schoolRepository, int schoolId)
      {
          return schoolRepository.GetById(schoolId);
      }

      public List<Class> GetClasses([Service] IClassRepository classRepository)
      {
          return classRepository.All();
      }
      public Class GetClassById([Service] IClassRepository classRepository, int classId)
      {
          return classRepository.GetById(classId);
      }

      public List<Class> GetClassesBySchoolId([Service] IClassRepository classRepository, int schoolId)
      {
          return classRepository.GetBySchool(schoolId);
      }

      public List<Student> GetStudents([Service] IStudentRepository studentRepository)
      {
          return studentRepository.All();
      }
      public Student GetStudentById([Service] IStudentRepository studentRepository, int studentId)
      {
          return studentRepository.GetById(studentId);
      }

      public List<Student> GetStudentsBySchoolId([Service] IStudentRepository studentRepository, int classId)
      {
          return studentRepository.GetByClass(classId);
      }
  }
}

At this point (apart from the fact we haven't configured the startup file with our DI) you will now have a Graph QL API but it won't be able to load any related items. You will however be able to pick which fields you want from the datasets.

To add the related data we need to create extension methods for our models. These inject the instance of the item using Hot Chocolates Parent attribute, and the repository we're going to use to get the data.

using AzureFunctionWithGraphApi.DataAccess;
using AzureFunctionWithGraphApi.Models;
using HotChocolate;
using HotChocolate.Types;
using System.Collections.Generic;

namespace AzureFunctionWithGraphApi
{
  [ExtendObjectType(typeof(School))]
  public class SchoolExtensions
  {
      public List<Class> GetClasses([Parent] School school, [Service] IClassRepository classRepository)
      {
          return classRepository.GetBySchool(school.Id);
      }
  }

  [ExtendObjectType(typeof(Class))]
  public class ClassExtensions
  {
      public School GetSchool([Parent] Class schoolClass, [Service] ISchoolRepository schoolRepository)
      {
          return schoolRepository.GetById(schoolClass.SchoolId);
      }
      public List<Student> GetStudents([Parent] Class schoolClass, [Service] IStudentRepository studentRepository)
      {
          return studentRepository.GetByClass(schoolClass.Id);
      }
  }

  [ExtendObjectType(typeof(Student))]
  public class StudentExtensions
  {
      public Class GetClass([Parent] Student student, [Service] IClassRepository classRepository)
      {
          return classRepository.GetById(student.ClassId);
      }
  }
}

Now all that's left is to configure our startup file. This file no longer gets created when you create the Azure Function so you'll need to add it yourself.

Here's mine. As you can see I'm registering the dependency injection for my repositories, and also configuring the GraphQL. This needs to include the query class we made and any extension classes.

using AzureFunctionWithGraphApi.DataAccess;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;

[assembly: FunctionsStartup(typeof(AzureFunctionWithGraphApi.Startup))]
namespace AzureFunctionWithGraphApi
{
  public class Startup : FunctionsStartup
  {
      public override void Configure(IFunctionsHostBuilder builder)
      {
          builder.Services.AddScoped<ISchoolRepository, SchoolRepository>();
          builder.Services.AddScoped<IClassRepository, ClassRepository>();
          builder.Services.AddScoped<IStudentRepository, StudentRepository>();

          builder.AddGraphQLFunction()
              .AddQueryType<Query>()
              .AddTypeExtension<SchoolExtensions>()
              .AddTypeExtension<ClassExtensions>()
              .AddTypeExtension<StudentExtensions>();
      }
  }
}

Run the Application and navigate in a browser to it's one route and you should get see the Banana Cake Pop UI to be able to view your schema.

Banana Cake Pop UI showing Scheme Reference

You can also test out queries selecting just the data you want even on related items.

Banana Cake Pop UI showing Query

We could even start with selecting a specific student and pull in their related class and school info.

Banana Cake Pop Graph QL Query

The Bad News

All of this is great and in fact, even more, functionality is available to be added, but there is some bad news. Not all of Hot Chocolates functionality actually works in an Azure Function, specifically authentication.

You can read about Hot Chocolates implementation of Authentication and Authorization here however it uses ASP.NET Core authentication middleware and Authorize attributes which do not work in Azure Functions. So unless you want your Graph QL API to be fully public you may be out of luck with this being a solution.

Code for this Demo

Now for the good news, if you want to try this without typing all the code, you can get a copy of it from my GitHub here.

https://github.com/timgriff84/AzureFunctionWithGraphApi