Monday, 30 November 2026

Snowstorm Snomed C# MinimalApi and Blazor Client Demo

I created a Snowstorm C# Minimal API and a Blazor Client Demo using Snowstorm Snomed local server to query after Snomed CT codes and display hierarhical relations, that is descendants and ancestors of a Snomed Clinical Term , abbreviated Snomed CT. The Github repository of mine for the source code in this article is available here:

https://github.com/toreaurstadboss/Snowstorm.Snowmed.CSharp

The Minimal Api also retrieves descriptions and synonyms for Snomed CT. A generated client to consume the local Snomed Snowstorm server is available in the file `Snowstormclient.cs` in the Minimal Api. Note : The ISnowstormClient is the generated client using NSwagstudio pointing against the Open API page for the Swagger page of the Snomed Snowstorm server running locally. You can download NSwagstudio from here: https://github.com/RicoSuter/NSwag/wiki/NSwagStudio This file is generated by running the Snomed Snowstorm server using this command in the Server folder:


docker compose up -d


The docker-compose.yml YAML file is available here: https://github.com/toreaurstadboss/Snowstorm.Snowmed.CSharp/blob/5508d03918aacb34554fb30bccfe2337ca7add3e/Server/docker-compose.yml

Docker-compose.yml for Snowstorm Snomed server


# https://github.com/IHTSDO/snowstorm/blob/master/docker-compose.yml

services:
  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:8.19.8
    container_name: elasticsearch
    environment:
      - discovery.type=single-node
      - xpack.security.enabled=false
      - node.name=snowstorm
      - cluster.name=snowstorm-cluster
      - "ES_JAVA_OPTS=-Xms4g -Xmx4g"
    volumes:
      - elastic:/usr/share/elasticsearch/data
    networks:
      elastic:
        aliases:
         - es
    healthcheck:
      test: ["CMD", "curl", "-f", "http://es:9200"]
      interval: 1s
      timeout: 1s
      retries: 60
    ports:
      - 127.0.0.1:9200:9200
    mem_reservation: 4g

  snowstorm:
    image: snomedinternational/snowstorm:latest
    depends_on:
      elasticsearch:
        condition: service_healthy
    environment:
      - elasticsearch.urls=http://elasticsearch:9200
      - JAVA_TOOL_OPTIONS=-Xms2g -Xmx4g --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.util=ALL-UNNAMED
    command: [
      "--elasticsearch.urls=http://es:9200",
    ]
    networks:
      elastic:
        aliases:
         - snowstorm
    ports:
      - "8080:8080"
    volumes:
      - ./rf2:/rf2

networks:
  elastic:
    name: elastic

volumes:
  elastic:



Minimal Api

The Concepts methods for the Snomed CT is gathered in a Minimal Api endpoints are gathered in the IEndpointRouteBuilder extension methods shown below. Note : The ISnowstormClient is the generated client using NSwagstudio pointing against the Open API page for the Swagger page of the Snomed Snowstorm server running locally.

ConceptEndpoints.cs



using Microsoft.AspNetCore.Http.HttpResults;
using System.ComponentModel;

namespace Snowstorm.Snomed.Csharp.MinimalApi;

/// <summary>
/// Maps concept search and lookup endpoints.
/// </summary>
public static class ConceptEndpoints
{
    /// <summary>
    /// Maps the concept search and lookup endpoints.
    /// </summary>
    /// <param name="app">The endpoint route builder.</param>
    /// <param name="branch">The Snowstorm branch to query.</param>
    /// <returns>The endpoint route builder.</returns>
    public static IEndpointRouteBuilder MapConceptEndpoints(this IEndpointRouteBuilder app, string branch = "MAIN")
    {

        //GET: Search concepts by name : /api/concepts
        app.MapGet(
         "/api/concepts/{conceptId}/parents",
         [EndpointName("GetConceptParentsById")]
        [EndpointSummary("Get direct parents of a concept")]
        [EndpointDescription("Returns the direct parents of a SNOMED CT concept.")]
        async Task<Results<Ok<IReadOnlyList<ConceptResponse>>, BadRequest<string>>> (
             [Description("The SNOMED CT concept identifier.")] string conceptId,
             ISnowstormClient snowstormClient,
             IEndpointUtil endpointUtil,
             CancellationToken cancellationToken) =>
         {
             return await endpointUtil.GetListAsync(
                 conceptId,
                 (searchTerm, token) => ConceptEndpointsImplementation.SearchConceptParentsAsync(
                     snowstormClient,
                     branch,
                     searchTerm,
                     token),
                 cancellationToken);
         });

        app.MapGet(
                "/api/concepts",
                [EndpointName("SearchConcepts")]
        [EndpointSummary("Search concepts by name")]
        [EndpointDescription("Returns matching active SNOMED CT concepts with their preferred name and concept identifier.")]
        async Task<Results<Ok<IReadOnlyList<ConceptResponse>>, BadRequest<string>>> (
                    [Description("The concept name or term to search for.")] string? term,
                    ISnowstormClient snowstormClient,
                    IEndpointUtil endpointUtil,
                    CancellationToken cancellationToken) =>
                {
                    return await endpointUtil.GetListAsync(
                        term,
                        (searchTerm, token) => ConceptEndpointsImplementation.SearchConceptsAsync(
                            snowstormClient,
                            branch,
                            searchTerm,
                            token),
                        cancellationToken);
                });

        //GET: Search concepts by identifier : /api/concepts/{conceptId}
        app.MapGet(
                "/api/concepts/{conceptId}",
                [EndpointName("GetConceptById")]
        [EndpointSummary("Get a concept by identifier")]
        [EndpointDescription("Returns an active SNOMED CT concept with the requested identifier.")]
        async Task<Results<Ok<ConceptResponse>, NotFound>> (
                    [Description("The SNOMED CT concept identifier.")] string conceptId,
                    ISnowstormClient snowstormClient,
                    CancellationToken cancellationToken) =>
                {
                    var concept = await ConceptEndpointsImplementation.GetConceptByIdAsync(
                        snowstormClient,
                        branch,
                        conceptId,
                        cancellationToken);

                    return concept is null
                        ? TypedResults.NotFound()
                        : TypedResults.Ok(concept);
                });

        app.MapGet(
            "/api/concepts/{conceptId}/descriptions",
            [EndpointName("GetConceptDescriptionsById")]
        [EndpointSummary("Get concept descriptions by identifier")]
        async Task<Results<Ok<IReadOnlyList<ConceptDescriptionResponse>>, BadRequest<string>>> (string conceptId,
            ISnowstormClient snowstormClient,
            IEndpointUtil endpointUtil,
            CancellationToken cancellationToken) =>
            {
                var concepts = await endpointUtil.GetListAsync(
                    conceptId,
                    (searchTerm, token) => ConceptEndpointsImplementation.SearchConceptDescriptionsAsync(
                        snowstormClient,
                        branch,
                        searchTerm,
                        token),
                    cancellationToken);
                return concepts;
            });

        app.MapGet(
            "/api/concepts/{conceptId}/descendants",
            [EndpointName("GetConceptDescendantsById")]
        [EndpointSummary("Get conceptdescendants by identifier")]
        async Task<Results<Ok<IReadOnlyList<ConceptResponse>>, BadRequest<string>>> (string conceptId,
            ISnowstormClient snowstormClient,
            IEndpointUtil endpointUtil,
            CancellationToken cancellationToken) =>
            {
                var descendants = await endpointUtil.GetListAsync(
                    conceptId,
                    (searchTerm, token) => ConceptEndpointsImplementation.SearchConceptDescendantsAsync(
                        snowstormClient,
                        branch,
                        searchTerm,
                        token),
                    cancellationToken);

                return descendants;
            });

        app.MapGet(
         "/api/concepts/{conceptId}/ancestors",
         [EndpointName("GetConceptAncestorsById")]
        [EndpointSummary("Get conceptancestors by identifier")]
        async Task<Results<Ok<IReadOnlyList<ConceptResponse>>, BadRequest<string>>> (string conceptId,
         ISnowstormClient snowstormClient,
         IEndpointUtil endpointUtil,
         CancellationToken cancellationToken) =>
         {
             var ancestors = await endpointUtil.GetListAsync(
                 conceptId,
                 (searchTerm, token) => ConceptEndpointsImplementation.SearchConceptAncestorsAsync(
                     snowstormClient,
                     branch,
                     searchTerm,
                     token),
                 cancellationToken);

             return ancestors;
         });

        return app;
    }
}



The ConceptEndpointsImplementation static class contains the static methods that implement the retrieval of Concepts using the generated client for the local Snowstorm Snomed CT server.

ConceptEndpointsImplementation.cs



using System.Text.Json;

namespace Snowstorm.Snomed.Csharp.MinimalApi;

/// <summary>
/// Provides helper operations for concept endpoints.
/// </summary>
internal static class ConceptEndpointsImplementation
{
    internal static async Task<ConceptResponse?> GetConceptByIdAsync(
        ISnowstormClient snowstormClient,
        string branch,
        string conceptId,
        CancellationToken cancellationToken)
    {
        var searchResult = await QueryConceptsAsync(
            snowstormClient,
            branch,
            term: null,
            conceptIds: [conceptId],
            limit: 1,
            cancellationToken);

        var concept = searchResult.Items.FirstOrDefault();
        return concept is null ? null : MapConcept(concept);
    }

    private static Task<ItemsPage> QueryConceptsAsync(
        ISnowstormClient snowstormClient,
        string branch,
        string? term,
        IEnumerable<string>? conceptIds,
        int limit,
        CancellationToken cancellationToken)
    {
        return snowstormClient.FindConceptsAsync(
            branch,
            activeFilter: true,
            definitionStatusFilter: null,
            module: null,
            term: term,
            termActive: true,
            descriptionType: null,
            language: ["en"],
            preferredIn: null,
            acceptableIn: null,
            preferredOrAcceptableIn: null,
            ecl: null,
            effectiveTime: null,
            isNullEffectiveTime: null,
            isPublished: null,
            statedEcl: null,
            includeLeafFlag: null,
            form: null,
            conceptIds: conceptIds,
            returnIdOnly: false,
            offset: 0,
            limit: limit,
            searchAfter: null,
            accept_Language: "en",
            cancellationToken);
    }

    private static Task<ItemsPageDescription_Component> QueryDescriptionsAsync(
        ISnowstormClient snowstormClient,
        string branch,
        string conceptId,
        IEnumerable<string>? conceptIds,
        int? limit,
        int? offset,
        CancellationToken cancellationToken)
    {
        return snowstormClient.FindDescriptionsAsync(
            branch,
            conceptIds: conceptIds,
            conceptId: conceptId,
            limit: limit,
            descriptionIds: null,
            offset: offset,
            cancellationToken: cancellationToken);
    }

    internal static async Task<IReadOnlyList<ConceptResponse>> SearchConceptDescendantsAsync(
        ISnowstormClient snowstormClient,
        string branch,
        string conceptId,
        CancellationToken token,
        bool? stated = null,
        int? offset = null,
        int? limit = null,
        string? acceptLanguage = null
        )
    {
        var descendants = await snowstormClient.FindConceptDescendantsAsync(branch, conceptId, stated, offset, limit, acceptLanguage, token);
        return descendants.Items.Select(MapConcept).OrderBy(c => c.Name).ToArray();
    }

    internal static async Task<IReadOnlyList<ConceptResponse>> SearchConceptParentsAsync(
        ISnowstormClient snowstormClient,
        string branch,
        string conceptId,
        CancellationToken cancellationToken)
    {
        var parents = await snowstormClient.FindConceptParentsAsync(
            branch, conceptId, form: null, includeDescendantCount: null, accept_Language: "en", cancellationToken);

        return parents
            .Select(parent => new ConceptResponse(parent.Pt.Term, parent.ConceptId))
            .OrderBy(parent => parent.Name)
            .ToArray();
    }

    internal static async Task<IReadOnlyList<ConceptResponse>> SearchConceptAncestorsAsync(
      ISnowstormClient snowstormClient,
      string branch,
      string conceptId,
      CancellationToken token,
      Form4? form = null,
      string? acceptLanguage = null
      )
    {
        var descendants = await snowstormClient.FindConceptAncestorsAsync(branch, conceptId, form, acceptLanguage, token);
        return descendants.Select(MapConcept).OrderBy(c => c.Name).ToArray();
    }

    internal static async Task<IReadOnlyList<ConceptDescriptionResponse>> SearchConceptDescriptionsAsync(
        ISnowstormClient snowstormClient,
        string branch,
        string conceptId,
        CancellationToken cancellationToken)
    {
        var searchResult = await QueryDescriptionsAsync(
            snowstormClient,
            branch,
            conceptId: conceptId,
            conceptIds: null,
            limit: 100,
            offset: 0,
            cancellationToken: cancellationToken);

        return searchResult.Items
            .Select(MapConceptDescription)
            .ToArray();
    }

    internal static async Task<IReadOnlyList<ConceptResponse>> SearchConceptsAsync(
        ISnowstormClient snowstormClient,
        string branch,
        string term,
        CancellationToken cancellationToken)
    {
        var searchResult = await QueryConceptsAsync(
            snowstormClient,
            branch,
            term,
            conceptIds: null,
            limit: 100,
            cancellationToken);

        return searchResult.Items
            .Select(MapConcept)
            .OrderBy(c => c.Name)
            .ToArray();
    }

    private static ConceptResponse MapConcept(object item)
    {
        var concept = item switch
        {
            ConceptMini conceptMini => conceptMini,
            JsonElement jsonElement => jsonElement.Deserialize<ConceptMini>()
                ?? throw new InvalidOperationException("Snowstorm returned an empty concept."),
            _ => throw new InvalidOperationException("Snowstorm returned a concept in an unexpected format.")
        };

        return new ConceptResponse(concept.Pt.Term, concept.ConceptId);
    }

    private static ConceptDescriptionResponse MapConceptDescription(object item)
    {
        var conceptDescription = item switch
        {
            Description_Component description => description,
            JsonElement jsonElement => jsonElement.Deserialize<Description_Component>()
                ?? throw new InvalidOperationException("Snowstorm returned an empty concept."),
            _ => throw new InvalidOperationException("Snowstorm returned a concept in an unexpected format.")
        };

        return new ConceptDescriptionResponse(conceptDescription.Term, conceptDescription.DescriptionId, conceptDescription.Type, conceptDescription.ConceptId);
    }

}



Please note the tailored deserialization of ConceptMini done above here to get concepts and concept description. Most often we do type safe access to Snowstorm Snomed Ct objects, but now and then we have to resort to tailored Json deserializaton shown above in the code snippet. The EndpointUtil contains some helper methods for Minimal Api to retrieve list objects or BadRequest, similar to a Maybe monad. It is often used in Minimal Api

EndpointUtil.cs



using Microsoft.AspNetCore.Http.HttpResults;

namespace Snowstorm.Snomed.Csharp.MinimalApi;

/// <summary>
/// Provides common behavior for search endpoints.
/// </summary>
public interface IEndpointUtil
{
    /// <summary>
    /// Validates a search term and returns the matching results.
    /// </summary>
    /// <typeparam name="TResponse">The response item type.</typeparam>
    /// <param name="term">The search term supplied by the request.</param>
    /// <param name="searchAsync">The search operation to execute for a valid term.</param>
    /// <param name="cancellationToken">The token used to cancel the search.</param>
    /// <returns>A bad request for a missing term or the search results.</returns>
    Task<Results<Ok<IReadOnlyList<TResponse>>, BadRequest<string>>> GetListAsync<TResponse>(
        string? term,
        Func<string, CancellationToken, Task<IReadOnlyList<TResponse>>> searchAsync,
        CancellationToken cancellationToken);
}

/// <summary>
/// Implements common behavior for search endpoints.
/// </summary>
public sealed class EndpointUtil : IEndpointUtil
{
    public async Task<Results<Ok<IReadOnlyList<TResponse>>, BadRequest<string>>> GetListAsync<TResponse>(
        string? term,
        Func<string, CancellationToken, Task<IReadOnlyList<TResponse>>> searchAsync,
        CancellationToken cancellationToken)
    {
        ArgumentNullException.ThrowIfNull(searchAsync);

        if (string.IsNullOrWhiteSpace(term))
        {
            return TypedResults.BadRequest("A search term must be provided in the 'term' query parameter.");
        }

        var results = await searchAsync(term, cancellationToken);
        return TypedResults.Ok(results);
    }
}



Blazor client using the Minimal Api consuming the local Snowstorm Snomed CT server

Here are some screenshots showing a Blazor client using the Minimal Api consuming the local Snowstorm Snomed CT server.
Screenshots for the Blazor client

No comments:

Post a Comment