获取 FHIR 资源。
包含此代码示例的文档页面
如需查看上下文中使用的代码示例,请参阅以下文档:
代码示例
Go
import (
"context"
"fmt"
"io"
"io/ioutil"
healthcare "google.golang.org/api/healthcare/v1"
)
// getFHIRResource gets an FHIR resource.
func getFHIRResource(w io.Writer, projectID, location, datasetID, fhirStoreID, resourceType, fhirResourceID string) error {
ctx := context.Background()
healthcareService, err := healthcare.NewService(ctx)
if err != nil {
return fmt.Errorf("healthcare.NewService: %v", err)
}
fhirService := healthcareService.Projects.Locations.Datasets.FhirStores.Fhir
name := fmt.Sprintf("projects/%s/locations/%s/datasets/%s/fhirStores/%s/fhir/%s/%s", projectID, location, datasetID, fhirStoreID, resourceType, fhirResourceID)
call := fhirService.Read(name)
call.Header().Set("Content-Type", "application/fhir+json;charset=utf-8")
resp, err := call.Do()
if err != nil {
return fmt.Errorf("Read: %v", err)
}
defer resp.Body.Close()
respBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("could not read response: %v", err)
}
if resp.StatusCode > 299 {
return fmt.Errorf("Read: status %d %s: %s", resp.StatusCode, resp.Status, respBytes)
}
fmt.Fprintf(w, "%s", respBytes)
return nil
}
Java
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Collections;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
public class FhirResourceGet {
private static final String FHIR_NAME =
"projects/%s/locations/%s/datasets/%s/fhirStores/%s/fhir/%s/%s";
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();
public static void fhirResourceGet(String resourceName) throws IOException, URISyntaxException {
// String resourceName =
// String.format(
// FHIR_NAME, "project-id", "region-id", "dataset-id", "store-id", "resource-type",
// "resource-id");
// Initialize the client, which will be used to interact with the service.
CloudHealthcare client = createClient();
HttpClient httpClient = HttpClients.createDefault();
String uri = String.format("%sv1/%s", client.getRootUrl(), resourceName);
URIBuilder uriBuilder = new URIBuilder(uri).setParameter("access_token", getAccessToken());
HttpUriRequest request = RequestBuilder.get().setUri(uriBuilder.build()).build();
// Execute the request and process the results.
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
String errorMessage =
String.format(
"Exception retrieving FHIR resource: %s\n", response.getStatusLine().toString());
System.err.print(errorMessage);
responseEntity.writeTo(System.err);
throw new RuntimeException(errorMessage);
}
System.out.println("FHIR resource retrieved: ");
responseEntity.writeTo(System.out);
}
private static CloudHealthcare createClient() throws IOException {
// Use Application Default Credentials (ADC) to authenticate the requests
// For more information see https://cloud.google.com/docs/authentication/production
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));
// Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
HttpRequestInitializer requestInitializer =
request -> {
new HttpCredentialsAdapter(credential).initialize(request);
request.setConnectTimeout(60000); // 1 minute connect timeout
request.setReadTimeout(60000); // 1 minute read timeout
};
// Build the client for interacting with the service.
return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
.setApplicationName("your-application-name")
.build();
}
private static String getAccessToken() throws IOException {
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));
return credential.refreshAccessToken().getTokenValue();
}
}
Node.js
const {google} = require('googleapis');
const healthcare = google.healthcare('v1');
const getFhirResource = async () => {
const auth = await google.auth.getClient({
scopes: ['https://www.googleapis.com/auth/cloud-platform'],
});
google.options({auth});
// TODO(developer): uncomment these lines before running the sample
// const cloudRegion = 'us-central1';
// const projectId = 'adjective-noun-123';
// const datasetId = 'my-dataset';
// const fhirStoreId = 'my-fhir-store';
// const resourceType = 'Patient';
// const resourceId = '16e8a860-33b3-49be-9b03-de979feed14a';
const name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir/${resourceType}/${resourceId}`;
const request = {name};
const resource = await healthcare.projects.locations.datasets.fhirStores.fhir.read(
request
);
console.log(`Got ${resourceType} resource:\n`, resource.data);
};
getFhirResource();
Python
def get_resource(
base_url,
project_id,
cloud_region,
dataset_id,
fhir_store_id,
resource_type,
resource_id,
):
"""Gets a FHIR resource."""
url = "{}/projects/{}/locations/{}".format(base_url, project_id, cloud_region)
resource_path = "{}/datasets/{}/fhirStores/{}/fhir/{}/{}".format(
url, dataset_id, fhir_store_id, resource_type, resource_id
)
# Make an authenticated API request
session = get_session()
headers = {"Content-Type": "application/fhir+json;charset=utf-8"}
response = session.get(resource_path, headers=headers)
response.raise_for_status()
resource = response.json()
print("Got {} resource:".format(resource["resourceType"]))
print(json.dumps(resource, indent=2))
return resource