5

I have an ASP.Net Web API 2 endpoint that supports OData queries. It is as such:

[HttpGet, Route("")]
public IQueryable<Thing> Get()
{
    return _thingsRepository.Query();
}

The OData $filter parameter and such work great. I just wish they would show up in Swagger like they do for actual OData controllers.

I am using Swashbuckle.OData ... but I'm really not sure that it's buying me anything in this case.

3 Answers 3

7

It turns out it's pretty easy to add whatever parameters you want to Swagger using SwashBuckle using an IOperationFilter. You can add it in your Swagger Configuration using c.OperationFilter<ODataParametersSwaggerDefinition>();. I created one that adds some OData Parameters to all IQueryable endpoints in my API:

/// <summary>
///     Add the supported odata parameters for IQueryable endpoints.
/// </summary>
public class ODataParametersSwaggerDefinition : IOperationFilter
{
    private static readonly Type QueryableType = typeof(IQueryable);

    /// <summary>
    ///     Apply the filter to the operation.
    /// </summary>
    /// <param name="operation">The API operation to check.</param>
    /// <param name="schemaRegistry">The swagger schema registry.</param>
    /// <param name="apiDescription">The description of the api method.</param>
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        var responseType = apiDescription.ResponseType();

        if (responseType.GetInterfaces().Any(i => i == QueryableType))
        {
            operation.parameters.Add(new Parameter
            {
                name = "$filter",
                description = "Filter the results using OData syntax.",
                required = false,
                type = "string",
                @in = "query"
            });

            operation.parameters.Add(new Parameter
            {
                name = "$orderby",
                description = "Order the results using OData syntax.",
                required = false,
                type = "string",
                @in = "query"
            });

            operation.parameters.Add(new Parameter
            {
                name = "$skip",
                description = "The number of results to skip.",
                required = false,
                type = "integer",
                @in = "query"
            });

            operation.parameters.Add(new Parameter
            {
                name = "$top",
                description = "The number of results to return.",
                required = false,
                type = "integer",
                @in = "query"
            });

            operation.parameters.Add(new Parameter
            {
                name = "$count",
                description = "Return the total count.",
                required = false,
                type = "boolean",
                @in = "query"
            });
        }
    }
}
2

Direct steal of the accepted answer, but, with extra null check.

This will not touch your existing OData queryable endpoints which may already have parameters defined, but, will only enhance your queryable ApiController endpoints.

Updated AspNetCore / Net 5, Net 6 Answer

using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.Linq;

namespace My.Corporation.Api
{
    /// <summary>
    /// Help your swagger show OData query options with example pre-fills
    /// </summary>
    public class ODataParametersSwaggerDefinition : IOperationFilter
    {
        private static readonly Type QueryableType = typeof(IQueryable);
        private static readonly OpenApiSchema stringSchema = new OpenApiSchema { Type = "string" };
        private static readonly OpenApiSchema intSchema = new OpenApiSchema { Type = "integer" };

        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            var hasNoParams = (operation.Parameters == null || operation.Parameters.Count == 0);
            var isQueryable = context.MethodInfo.ReturnType.GetInterfaces().Any(i => i == QueryableType);

            if (hasNoParams && isQueryable)
            {

                operation.Parameters = new List<OpenApiParameter>();
                operation.Parameters.Add(new OpenApiParameter
                {
                    Name = "$filter",
                    Description = "Filter the results using OData syntax.",
                    Example = OpenApiAnyFactory.CreateFor(stringSchema,"ProductName eq 'YOGURT'"),
                    Required = false,
                    In = ParameterLocation.Query,
                    Schema = stringSchema

                });
                operation.Parameters.Add(new OpenApiParameter
                {
                    Name = "$select",
                    Description = "Trim the fields returned using OData syntax",
                    Example = OpenApiAnyFactory.CreateFor(stringSchema, "Id,ProductName"),
                    Required = false,
                    In = ParameterLocation.Query,
                    Schema = new OpenApiSchema { Type = "string" }
                });
                operation.Parameters.Add(new OpenApiParameter
                {
                    Name = "$orderby",
                    Description = "Order the results using OData syntax.",
                    Example = OpenApiAnyFactory.CreateFor(stringSchema, "Price,ProductName ASC"),
                    Required = false,
                    In = ParameterLocation.Query,
                    Schema = new OpenApiSchema { Type = "string" }
                });
                operation.Parameters.Add(new OpenApiParameter
                {
                    Name = "$skip",
                    Description = "The number of results to skip.",
                    Example = OpenApiAnyFactory.CreateFor(intSchema, 100),
                    Required = false,
                    In = ParameterLocation.Query,
                    Schema = intSchema
                });
                operation.Parameters.Add(new OpenApiParameter
                {
                    Name = "$top",
                    Description = "The number of results to return.",
                    Example = OpenApiAnyFactory.CreateFor(intSchema, 50),
                    Required = false,
                    In = ParameterLocation.Query,
                    Schema = intSchema
                });
            }
        }
    }
}

Original WebAPI 2 Answer

 /// <summary>
 /// Adds the supported odata parameters for IQueryable endpoints 
 /// ONLY if no parameters are defined already.
 /// </summary>
 public class ODataParametersSwaggerDefinition : IOperationFilter
 {
    private static readonly Type QueryableType = typeof(IQueryable);

    /// <summary>
    /// Apply the filter to the operation.
    /// </summary>
    /// <param name="operation">The API operation to check.</param>
    /// <param name="schemaRegistry">The swagger schema registry.</param>
    /// <param name="apiDescription">The description of the api method.</param>
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        var responseType = apiDescription.ResponseType();

        if (responseType.GetInterfaces().Any(i => i == QueryableType))
        {
            if (operation.parameters == null)
            {
                operation.parameters = new List<Parameter>();

                operation.parameters.Add(new Parameter
                {
                    name = "$filter",
                    description = "Filter the results using OData syntax.",
                    required = false,
                    type = "string",
                    @in = "query"
                });

                operation.parameters.Add(new Parameter
                {
                    name = "$orderby",
                    description = "Order the results using OData syntax.",
                    required = false,
                    type = "string",
                    @in = "query"
                });

                operation.parameters.Add(new Parameter
                {
                    name = "$skip",
                    description = "The number of results to skip.",
                    required = false,
                    type = "integer",
                    @in = "query"
                });

                operation.parameters.Add(new Parameter
                {
                    name = "$top",
                    description = "The number of results to return.",
                    required = false,
                    type = "integer",
                    @in = "query"
                });

                operation.parameters.Add(new Parameter
                {
                    name = "$count",
                    description = "Return the total count.",
                    required = false,
                    type = "boolean",
                    @in = "query"
                });
            }
            
        }
    }
}
1

Using Swashbuckle.AspNetCore v. 6.2.3 it can look like this:

public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
    if (context.MethodInfo.ReturnType.GetInterfaces().Any(i => i == typeof(IQueryable)))
    {
        operation.Parameters.Add(new OpenApiParameter()
        {
            Name = "$filter",
            Description = "My $filter filter",
            Required = false,
            In = ParameterLocation.Query,                
        });

        operation.Parameters.Add(new OpenApiParameter()
        {
            Name = "$top",
            Description = "My $top filter",
            Required = false,
            In = ParameterLocation.Query,           
        });

        operation.Parameters.Add(new OpenApiParameter()
        {
            Name = "$expand",
            Description = "My $top filter",
            Required = false,
            In = ParameterLocation.Query,                
        });
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.