Snippets

Logica Accessing FHIR API with previously fetched access token

Created by Mike Bylund
package org.hspconsortium.client.example.controller;

import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.rest.client.IClientInterceptor;
import ca.uhn.fhir.rest.client.IGenericClient;
import ca.uhn.fhir.rest.client.api.IHttpRequest;
import ca.uhn.fhir.rest.client.api.IHttpResponse;
import org.hl7.fhir.dstu3.model.Bundle;
import org.hl7.fhir.dstu3.model.Patient;

import java.io.IOException;

public class StaticAccessTokenExampleController {

    // replace with a non-expired access token
    private static String ACCESS_TOKEN = "eyJhbGciOiJSUzI1NiJ9.eyJhdWQiOiJiaWxpcnViaW5fY2hhcnQiLCJpc3MiOiJodHRwczpcL1wvYXV0aC5oc3Bjb25zb3J0aXVtLm9yZ1wvIiwiZXhwIjoxNTExOTcwODA5LCJpYXQiOjE1MTE4ODQ0MDksImp0aSI6ImNhODE2YzE2LTcyY2MtNGQ3MC04NjBhLTNhZGJlZmRmYjhkNSJ9.iAvaA7toqtoq3NhyQHZRXm6YfLdxI7Y_RtjoFoRX_f7ury9Kp35L7J81ek2IViuFC2MtFotY_iyqI7Tc5MKaUDI_aLQfj-5xdzCO7B_4jUcm8f_8JKSOAB11H06s7Uk2ctH2xsxmk0PN5c7Y_ZzebwhKDyRuNUE_K77VImTogwSgrFEtRMVC42ck86rrQhTmIkSYMXPcDEnhdwlk71FH2CtbVCVnHQNMQwrFdbsKvkQOGPON7cvYLF9wql2RIAIa3R6002DgLaW0UZLJjY7jpOOsCn6n0yKjunK1Yfma8nHmPtFvPayx-NZgQHd3kWh5QbIaz45omkm0MxE0DlX1HA";
    
    // example patient resource ID
    private static String PATIENT_ID = "BILIBABY"; 
    
    // base URL of the FHIR server
    private static String FHIR_SERVER_BASE = "https://api-stu3.hspconsortium.org/stu3/data";

    
    private void fetchDataFromFhirApi() {
        FhirContext ctx = FhirContext.forDstu3();

        IGenericClient client = ctx.newRestfulGenericClient(FHIR_SERVER_BASE);
        client.registerInterceptor(new ClientAuthInterceptor());

        // Perform a search
        Bundle results = client
                .search()
                .forResource(Patient.class)
                .where(Patient.RES_ID.exactly().identifier(PATIENT_ID))
                .returnBundle(Bundle.class)
                .execute();

        System.out.println("Found " + results.getEntry().size() + " patients named 'duck'");
        System.out.println(results.getEntryFirstRep().getFullUrl());
    }

    public class ClientAuthInterceptor implements IClientInterceptor {
        @Override
        public void interceptRequest(IHttpRequest request) {
            request.addHeader("Authorization", "Bearer " + ACCESS_TOKEN);
        }

        @Override
        public void interceptResponse(IHttpResponse iHttpResponse) throws IOException {
            // do nothing
        }
    }
}

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.