Mt.GraphQL.Api.Server 1.4.0

dotnet add package Mt.GraphQL.Api.Server --version 1.4.0
                    
NuGet\Install-Package Mt.GraphQL.Api.Server -Version 1.4.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Mt.GraphQL.Api.Server" Version="1.4.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Mt.GraphQL.Api.Server" Version="1.4.0" />
                    
Directory.Packages.props
<PackageReference Include="Mt.GraphQL.Api.Server" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Mt.GraphQL.Api.Server --version 1.4.0
                    
#r "nuget: Mt.GraphQL.Api.Server, 1.4.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Mt.GraphQL.Api.Server@1.4.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Mt.GraphQL.Api.Server&version=1.4.0
                    
Install as a Cake Addin
#tool nuget:?package=Mt.GraphQL.Api.Server&version=1.4.0
                    
Install as a Cake Tool

Introduction

Using GraphQL queries, the client of your API can control how entities are returned by applying custom filtering, sorting, paging and/or selecting just one or a few of the entity's properties, all specified in the request. The Mt.GraphQL.Api.Server package makes it easy to expose data in your API using GraphQL queries, translating the GraphQL query to Linq to be able to apply it directly to the database, all within what is configured to be allowed.

For .NET clients, package Mt.GraphQL.Api.Client can be used.

Controllers

In your web project's controllers, the GraphQL queries are mapped to a generic Query object. The server library allows you to directly apply this query object to any IQueryable<> or IEnumerable<> of the entity's type. This means that you could optionally first filter the available data to make sure the client only retrieves what is allowed. You could of course also pass the query object to the business layer if your application pattern requires that. The Apply() function returns the requested data along with the used query parameters.

ASP.NET Core

[ApiController, Route("Contact")]
public class ContactController : ControllerBase
{
    [HttpGet]
    public ActionResult Get([FromQuery] Query<Contact> query)
    {
        // This part is only needed when the controller has no ApiController attribute.
        if (!ModelState.IsValid)
            return ModelState.ToBadRequest(ControllerContext);

        try
        {
            using var context = new DbContext();
            return Ok(context.Contacts.Apply(query));
        }
        catch (QueryException ex)
        {
            return BadRequest(ex.Message);
        }
    }
}

When using ApiController attributes on your controllers, you can remove the part that checks the model state. Instead, add the following to the application startup:

builder.Services.AddControllers()
    .ConfigureApiBehaviorOptions(
        opt => opt.InvalidModelStateResponseFactory = ctx => ctx.ModelState.ToBadRequest(ctx));

.NET Framework MVC 5

[HttpGet, Route("Contact")]
public ActionResult GetContacts(Query<Contact> query)
{
    if (!ModelState.IsValid)
        return ModelState.ToBadRequest(ControllerContext);

    try
    {
        using (var context = new DbContext())
        {
            return Json(context.Contacts.Apply(query), JsonRequestBehavior.AllowGet);
        }
    }
    catch (QueryException ex)
    {
        Response.StatusCode = (int)HttpStatusCode.BadRequest;
        return Content(ex.Message);
    }
}

The used ToBadRequest() method is the following extension method:

public static ActionResult ToBadRequest(this ModelStateDictionary modelState, ControllerContext context)
{
    context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
    var keys = modelState.Keys.ToArray();
    return new ContentResult
    {
        Content = modelState.Values
            .SelectMany((v, i) => v.Errors.Select(e => $"Error in {keys[i]}: {e.Exception?.Message ?? e.ErrorMessage}"))
            .Aggregate(string.Empty, (r, v) => r + "; " + v)
            .Substring(2)
    };
}

.NET Framework API

[HttpGet, Route("Contact")]
public IHttpActionResult GetContacts([FromUri]Query<Contact> query)
{
    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    try
    {
        using (var context = new DbContext())
        {
            return Ok(context.Contacts.Apply(query));
        }
    }
    catch (QueryException ex)
    {
        return BadRequest(ex.Message);
    }
}

Server configuration

To customize the way entities can be queried, they can be configured in the startup of the API using GraphqlConfiguration.Configure<>(). You can configure

  • the maximum page size, globally and per entity
  • which column to order by if not specified in the query
  • which columns can be used for fitering and sorting (to avoid poorly performing queries which filter on database columns that aren't indexed)
  • which serialization attributes should be applied to properties
  • which properties should be hidden
  • which navigation properties are Extensions (these properties are not returned by default, only when explicitly requested using an extend clause. See the Mt.GraphQL.Api.Client README for more info).

Configurations can also be applied to base classes using GraphqlConfiguration.ConfigureBase<>(). This way the configuration is applied to all classes that derive from the configured base class.

GraphqlConfiguration.DefaultMaxPageSize = 200;
GraphqlConfiguration.ConfigureBase<ModelBase>()
    .DefaultOrderBy(x => x.Id)
    .AllowFilteringAndSorting(x => x.Id);
GraphqlConfiguration.Configure<Customer>()
    .AllowFilteringAndSorting(x => x.Name)
    .ExcludeProperty(x => x.Contacts.First().Customer)
    .ExcludeProperty(x => x.Contacts.First().Customer_Id);
GraphqlConfiguration.Configure<Contact>()
    .AllowFilteringAndSorting(x => x.Name)
    .AllowFilteringAndSorting(x => x.Customer_Id)
    .ApplyAttribute(
        x => x.DateOfBirth,
        () => new JsonDateTimeConverterAttribute { Format = "yyyy-MM-dd" })
    .ExcludeProperty(x => x.Customer.Contacts)
    .IsExtension(x => x.Customer);

GraphQL configurations can get quite extensive. Therefore it is possible to put it in your configuration file, make sure it is available on Microsoft.Extensions.Configuration and call GraphqlConfiguration.FromConfiguration(). All settings except ApplyAttribute() can be read from the configuration.

{
    "GraphqlConfiguration": {
        "DefaultMaxPageSize": 200,
        "BaseConfigurations": {
            "ModelBase": {
                "DefaultOrderBy": "Id",
                "ExcludeAllProperties": true,
                "Properties": {
                    "Id": {
                        "AllowFilteringAndSorting": true,
                        "Exclude": false
                    }
                }
            }
        },
        "TypeConfigurations": {
            "Customer": {
                "Properties": {
                    "Name": { "AllowFilteringAndSorting": true },
                    "Contacts.Customer": { "Exclude": true },
                    "Contacts.Customer_Id": { "Exclude": true }
                }
            },
            "Contact": {
                "Properties": {
                    "Name": { "AllowFilteringAndSorting": true },
                    "Customer_Id": { "AllowFilteringAndSorting": true },
                    "DateOfBirth": { "AllowFilteringAndSorting": true },
                    "Customer.Code": { "Exclude": true },
                    "Customer": { "IsExtension": true }
                }
            }
        }
    }
}

Meta information

To get information about the data that will be returned, a meta information object can be requested using query string ?meta=true. The response will contain property names and types, along with information whether the property is indexed or if it is an extension.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.4.0 130 12/18/2024
1.3.0 138 12/13/2024
1.2.8 151 7/10/2024
1.2.7 169 3/1/2024
1.2.6 157 3/1/2024
1.2.5 139 2/29/2024
1.2.4 156 2/28/2024
1.2.3 133 2/26/2024
1.2.2 142 2/22/2024
1.2.1 162 2/20/2024
1.2.0 146 2/15/2024
1.1.0 191 1/9/2024
1.0.1 161 1/5/2024