Simple Code Example

This section provides a simple code example for using the FHIR API based on the HL7.FHIR package available in C#/.NET. First, in order to call the API one needs to be able to add headers to the client. This is done by creating a custom HttpClientHandler:

public class HeaderHandler : HttpClientHandler
{
    public string headerName { get; set; }
    public string headerValue { get; set; }
    protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (headerName != null && headerValue != null)
        {
            request.Headers.Add(headerName, headerValue);
        }

        return await base.SendAsync(request, cancellationToken);
    }
}

The API can now be called with the following:

using Hl7.Fhir.Model;
using Hl7.Fhir.Rest;
using System.Configuration;

// Setup settings
string _subscriptionKey = ConfigurationManager.AppSettings["subscriptionKey"] ?? ""; // TODO: Add key to App.config
var demoId = "MedicinalProduct/{TODO: INSERT YOUR ID HERE}";
var fhirUrl = "https://api.legemiddelverket.no/fhir-r4-hresept";

// Initiate the FHIR Client.
var settings = new FhirClientSettings()
{
    PreferredFormat = ResourceFormat.Json
};

// Note: A custom header is added for authentication purposes.
var handler = new HeaderHandler
{
    headerName = "Ocp-Apim-Subscription-Key",
    headerValue = _subscriptionKey
};
var client = new FhirClient(fhirUrl, settings, handler);

// The client can now be used to fetch a given resource. 
var medicinalProduct = await client.ReadAsync<MedicinalProduct>(demoId);