---
title: Read visit reports
description: Write a command-line program that finds the signed report of a dietitian visit, prints its sections and downloads the files in it.
section: Tutorials
order: 8
---

# Read visit reports

After a visit, the dietitian writes a report and signs it. You build a command-line program that finds a signed report, lists reports, prints the sections of one report and downloads the file of a section.

The API calls a dietitian a **specialist** and a visit a **booking**. The code uses the API's words. The text says dietitian and visit.

## Before you start

- You finished [Set up your project](/docs/tutorials/set-up-your-project). Your project has the `nurishd` client file and a Sandbox key in `NURISHD_API_KEY`.
- Your key has the scope `report:read`. It reads reports and sees `report.signed` events. Step 1 also needs `booking:write`. Run the key check from the setup tutorial to see your scopes.
- Your company has a signed BAA, a business associate agreement with Nurish'd. Care scopes need it. See [BAA handling](/docs/care/baa).
- A booked visit of a Sandbox patient. Run the tutorial [Book a visit with a dietitian](/docs/tutorials/book-a-dietitian-visit) up to `show`, and stop before `cancel`. Its `show` command prints the booking id. A canceled visit cannot be completed.
- The patient allowed reports. When you create a patient with a key that holds `report:read`, the patient is asked to allow `care.reports`. See [Connections](/docs/concepts/connections).
- Python only: the program uses the `requests` package from the setup tutorial.

## 1. Complete a visit in the Sandbox

In the Sandbox no real visit happens, so nothing signs a report. The Sandbox has a test helper for this. `POST /developer/v1/test-helper/booking/{booking_id}/complete/document` marks a visit of yours as done and signs a sample report. Its content is invented.

The helper works only with a Sandbox key. A Production key gets `403 test_mode_only`. In Production there is no helper: the dietitian signs a report after a real visit, and you learn about it in step 2.

The program starts with its imports and the function for this step.

```python
import sys
from pathlib import Path

import requests

from nurishd import NurishdError, call

EXTENSIONS = {
    "application/pdf": ".pdf",
    "image/png": ".png",
    "image/jpeg": ".jpg",
}

HINTS = {
    "scope_not_granted": "Your key lacks a scope, or your company has no signed BAA.",
    "test_mode_only": "This helper works with a Sandbox key only. Use a key that starts with nk-test-.",
    "booking_not_completable": "The booking was canceled or is already completed. Use a booking in status booked.",
    "connection_scope_not_granted": "The patient does not share reports. Connect the patient again and ask for care.reports.",
    "connection_not_active": "The patient revoked the connection. You can no longer read this patient's reports.",
    "not_found": "Nothing with this id is visible to your company. Check the id.",
}


def complete_booking(booking_id):
    path = f"/developer/v1/test-helper/booking/{booking_id}/complete/document"
    done = call("POST", path)
    print(f"Booking {done['booking_id']} is now {done['status']}.")
    print(f"A sample report was signed: {done['report_id']}")
```

```javascript
import { writeFileSync } from 'node:fs';
import { NurishdError, call } from './nurishd.js';

const EXTENSIONS = {
	'application/pdf': '.pdf',
	'image/png': '.png',
	'image/jpeg': '.jpg',
};

const HINTS = {
	scope_not_granted:
		'Your key lacks a scope, or your company has no signed BAA.',
	test_mode_only:
		'This helper works with a Sandbox key only. Use a key that starts with nk-test-.',
	booking_not_completable:
		'The booking was canceled or is already completed. Use a booking in status booked.',
	connection_scope_not_granted:
		'The patient does not share reports. Connect the patient again and ask for care.reports.',
	connection_not_active:
		"The patient revoked the connection. You can no longer read this patient's reports.",
	not_found: 'Nothing with this id is visible to your company. Check the id.',
};

async function completeBooking(bookingId) {
	const path = `/developer/v1/test-helper/booking/${bookingId}/complete/document`;
	const done = await call('POST', path);
	console.log(`Booking ${done.booking_id} is now ${done.status}.`);
	console.log(`A sample report was signed: ${done.report_id}`);
}
```

```typescript
import { writeFileSync } from 'node:fs';
import { NurishdError, call } from './nurishd.ts';
import type { Page } from './nurishd.ts';

async function completeBooking(bookingId: string) {
	const path = `/developer/v1/test-helper/booking/${bookingId}/complete/document`;
	const done = await call<{
		booking_id: string;
		report_id: string;
		status: string;
	}>('POST', path);
	console.log(`Booking ${done.booking_id} is now ${done.status}.`);
	console.log(`A sample report was signed: ${done.report_id}`);
}
```

```java
package tutorial;

import com.fasterxml.jackson.databind.JsonNode;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import tutorial.Nurishd.NurishdException;

static void completeBooking(String bookingId) {
    String path = "/developer/v1/test-helper/booking/%s/complete/document".formatted(bookingId);
    JsonNode done = Nurishd.call("POST", path);
    System.out.println("Booking " + done.path("booking_id").asText() + " is now "
            + done.path("status").asText() + ".");
    System.out.println("A sample report was signed: " + done.path("report_id").asText());
}
```

Run it with the booking id from the booking tutorial. Replace `python reports.py` with the command of your language.

- Python: `python reports.py complete BOOKING_ID`
- JavaScript: `node reports.js complete BOOKING_ID`
- TypeScript: `node reports.ts complete BOOKING_ID`
- Java: `mvn -q compile exec:java -Dexec.mainClass=tutorial.Reports -Dexec.args="complete BOOKING_ID"`

```text
python reports.py complete booking-0001
Booking booking-0001 is now meeting_completed.
A sample report was signed: report-0001
```

The visit is now `meeting_completed`, and the report id is in the answer. A booking that was canceled or is already completed answers `409 booking_not_completable`.

## 2. Learn that a report is signed

You do not need to keep asking the reports route. Nurish'd raises a `report.signed` event when a dietitian signs the report of a visit your company booked. An event is thin: it holds ids and never the report. `data.id` is the report id, and `data.booking` is the visit.

A webhook sends events to your server as they happen. See [Receive order webhooks](/docs/tutorials/receive-order-webhooks) for a server that receives them. Here you read the events by hand, with `GET /developer/v1/event/query/documents`. The `type` filter keeps one event type. Events are kept for 30 days, and your key sees only types its scopes allow.

```python
def list_events():
    answer = call(
        "GET",
        "/developer/v1/event/query/documents",
        params={"type": "report.signed", "size": 10},
    )
    if not answer["data"]:
        print("No report.signed event yet. Wait a few seconds and run it again.")
    for event in answer["data"]:
        data = event["data"]
        print(f"{event['created']}: report {data['id']} for booking {data.get('booking')}")
```

```javascript
async function listEvents() {
	const answer = await call('GET', '/developer/v1/event/query/documents', {
		params: { type: 'report.signed', size: 10 },
	});
	if (answer.data.length === 0) {
		console.log(
			'No report.signed event yet. Wait a few seconds and run it again.',
		);
	}
	for (const event of answer.data) {
		console.log(
			`${event.created}: report ${event.data.id} for booking ${event.data.booking}`,
		);
	}
}
```

```typescript
async function listEvents() {
	const answer = await call<Page<ReportEvent>>(
		'GET',
		'/developer/v1/event/query/documents',
		{ params: { type: 'report.signed', size: 10 } },
	);
	if (answer.data.length === 0) {
		console.log(
			'No report.signed event yet. Wait a few seconds and run it again.',
		);
	}
	for (const event of answer.data) {
		console.log(
			`${event.created}: report ${event.data.id} for booking ${event.data.booking}`,
		);
	}
}
```

```java
static void listEvents() {
    JsonNode answer = Nurishd.call(
            "GET",
            "/developer/v1/event/query/documents",
            Map.of("type", "report.signed", "size", 10),
            null);
    if (answer.path("data").isEmpty()) {
        System.out.println("No report.signed event yet. Wait a few seconds and run it again.");
    }
    for (JsonNode event : answer.path("data")) {
        System.out.println(event.path("created").asText() + ": report "
                + event.path("data").path("id").asText() + " for booking "
                + event.path("data").path("booking").asText());
    }
}
```

The event follows shortly after the helper answers. If the list is empty, wait a few seconds and run it again.

```text
python reports.py events
2026-11-19T15:10:00Z: report report-0001 for booking booking-0001
```

## 3. List the reports

`GET /care/v1/report/query/documents` returns a page of signed reports, newest first. All filters are optional: `patient`, `booking`, `from`, `to`, `page` and `size`. The list is thin. It holds ids and `signed_at`. You read one report to get its sections.

If you ask for one `booking` and no report of it is known yet, the call also looks for a signed report of that visit. A report whose event you missed still shows up.

```python
def list_reports(booking_id=None):
    params = {"booking": booking_id} if booking_id else {}
    answer = call("GET", "/care/v1/report/query/documents", params=params)
    if not answer["data"]:
        print("No signed report found.")
    for item in answer["data"]:
        print(f"{item['report_id']}: booking {item['booking_id']}, signed {item['signed_at']}")
```

```javascript
async function listReports(bookingId) {
	const params = bookingId ? { booking: bookingId } : {};
	const answer = await call('GET', '/care/v1/report/query/documents', {
		params,
	});
	if (answer.data.length === 0) console.log('No signed report found.');
	for (const item of answer.data) {
		console.log(
			`${item.report_id}: booking ${item.booking_id}, signed ${item.signed_at}`,
		);
	}
}
```

```typescript
async function listReports(bookingId?: string) {
	const params: Record<string, string> = bookingId
		? { booking: bookingId }
		: {};
	const answer = await call<Page<ReportItem>>(
		'GET',
		'/care/v1/report/query/documents',
		{ params },
	);
	if (answer.data.length === 0) console.log('No signed report found.');
	for (const item of answer.data) {
		console.log(
			`${item.report_id}: booking ${item.booking_id}, signed ${item.signed_at}`,
		);
	}
}
```

```java
static void listReports(String bookingId) {
    Map<String, Object> params = bookingId == null ? Map.of() : Map.of("booking", bookingId);
    JsonNode answer = Nurishd.call("GET", "/care/v1/report/query/documents", params, null);
    if (answer.path("data").isEmpty()) {
        System.out.println("No signed report found.");
    }
    for (JsonNode item : answer.path("data")) {
        System.out.println(item.path("report_id").asText() + ": booking "
                + item.path("booking_id").asText() + ", signed "
                + item.path("signed_at").asText());
    }
}
```

```text
python reports.py list booking-0001
report-0001: booking booking-0001, signed 2026-11-19T15:10:00Z
```

You see only signed reports. A report that is not signed yet is not visible to you, so it is not in the list. You also see only reports of visits your company booked, for patients whose connection is still `active`.

## 4. Read one report

`GET /care/v1/report/{report_id}/get/document` returns the report with its sections, lowest `section_order` first. Each section has a name, a `section_type` (`note`, `table`, `image`, `pdf` or `signature`) and two fields that matter here:

- `section_content` holds the text of the section as Markdown. An `image` or a `pdf` section has none.
- `has_file` is `true` when the section has a file to download.

The program decides by these two fields, not by the type. It prints the text if there is any. It says so if there is a file.

```python
def show_report(report_id):
    report = call("GET", f"/care/v1/report/{report_id}/get/document")
    name = report["specialist_snapshot"].get("full_name", "unknown")
    print(f"Report {report['report_id']}, signed {report['signed_at']} by {name}")
    for section in sorted(report["sections"], key=lambda s: s["section_order"]):
        print()
        print(f"== {section['section_name']} ({section['section_type']}) ==")
        if section.get("section_content"):
            print(section["section_content"])
        if section["has_file"]:
            print(f"A file is attached. Run: file {report_id} {section['section_id']}")
```

```javascript
async function showReport(reportId) {
	const report = await call(
		'GET',
		`/care/v1/report/${reportId}/get/document`,
	);
	const name = report.specialist_snapshot.full_name ?? 'unknown';
	console.log(
		`Report ${report.report_id}, signed ${report.signed_at} by ${name}`,
	);
	const sections = [...report.sections].sort(
		(a, b) => a.section_order - b.section_order,
	);
	for (const section of sections) {
		console.log();
		console.log(`== ${section.section_name} (${section.section_type}) ==`);
		if (section.section_content) console.log(section.section_content);
		if (section.has_file) {
			console.log(
				`A file is attached. Run: file ${reportId} ${section.section_id}`,
			);
		}
	}
}
```

```typescript
async function showReport(reportId: string) {
	const report = await call<Report>(
		'GET',
		`/care/v1/report/${reportId}/get/document`,
	);
	const name = report.specialist_snapshot.full_name ?? 'unknown';
	console.log(
		`Report ${report.report_id}, signed ${report.signed_at} by ${name}`,
	);
	const sections = [...report.sections].sort(
		(a, b) => a.section_order - b.section_order,
	);
	for (const section of sections) {
		console.log();
		console.log(`== ${section.section_name} (${section.section_type}) ==`);
		if (section.section_content) console.log(section.section_content);
		if (section.has_file) {
			console.log(
				`A file is attached. Run: file ${reportId} ${section.section_id}`,
			);
		}
	}
}
```

```java
static void showReport(String reportId) {
    JsonNode report = Nurishd.call("GET", "/care/v1/report/%s/get/document".formatted(reportId));
    String name = report.path("specialist_snapshot").path("full_name").asText("unknown");
    System.out.println("Report " + report.path("report_id").asText() + ", signed "
            + report.path("signed_at").asText() + " by " + name);
    List<JsonNode> sections = new ArrayList<>();
    report.path("sections").forEach(sections::add);
    sections.sort(Comparator.comparingInt(s -> s.path("section_order").asInt()));
    for (JsonNode section : sections) {
        System.out.println();
        System.out.println("== " + section.path("section_name").asText() + " ("
                + section.path("section_type").asText() + ") ==");
        if (!section.path("section_content").asText("").isEmpty()) {
            System.out.println(section.path("section_content").asText());
        }
        if (section.path("has_file").asBoolean()) {
            System.out.println("A file is attached. Run: file " + reportId + " "
                    + section.path("section_id").asText());
        }
    }
}
```

```text
python reports.py show report-0001
Report report-0001, signed 2026-11-19T15:10:00Z by Maya Okafor

== Summary (note) ==
You are on track. Keep the plan for two weeks.

== Lab results (pdf) ==
A file is attached. Run: file report-0001 section-0002
```

The report holds only what the dietitian shared with the patient. Private notes and the patient's own details are never part of it.

## 5. Download the file of a section

For a section with `has_file: true`, call `GET /care/v1/report/{report_id}/section/{section_id}/file/get/document`. The answer is a small JSON object with a `url`. The link works for a short time only. The client reads that answer as it reads every other.

The download itself is a plain request to that link. The link points to a file host, not to the Nurish'd API, so the program does not use the client for it. The client adds your API key to every request, and your key must never go to another host. The program uses the standard HTTP tool of each language instead: `requests`, `fetch` and `java.net.http`. The answer is the file's bytes, so the program writes them to disk. It names the file from its content type.

Fetch the link when the person asks for the file. Do not store the link, and do not print or log it. Run the route again when you need the file again.

```python
EXTENSIONS = {
    "application/pdf": ".pdf",
    "image/png": ".png",
    "image/jpeg": ".jpg",
}


def download_file(report_id, section_id):
    path = f"/care/v1/report/{report_id}/section/{section_id}/file/get/document"
    link = call("GET", path)
    # The link points to a file host, not to the API. Do not send your key to it.
    res = requests.get(link["url"], timeout=30)
    if not res.ok:
        sys.exit("The link did not work. Run this command again to get a new one.")
    kind = res.headers.get("Content-Type", "").split(";")[0]
    name = section_id + EXTENSIONS.get(kind, ".bin")
    Path(name).write_bytes(res.content)
    print(f"Saved {len(res.content)} bytes to {name}.")
```

```javascript
const EXTENSIONS = {
	'application/pdf': '.pdf',
	'image/png': '.png',
	'image/jpeg': '.jpg',
};

async function downloadFile(reportId, sectionId) {
	const path = `/care/v1/report/${reportId}/section/${sectionId}/file/get/document`;
	const link = await call('GET', path);
	// The link points to a file host, not to the API. Do not send your key to it.
	const res = await fetch(link.url);
	if (!res.ok) {
		exitWith(
			'The link did not work. Run this command again to get a new one.',
		);
	}
	const kind = (res.headers.get('content-type') ?? '').split(';')[0];
	const name = sectionId + (EXTENSIONS[kind] ?? '.bin');
	const bytes = Buffer.from(await res.arrayBuffer());
	writeFileSync(name, bytes);
	console.log(`Saved ${bytes.length} bytes to ${name}.`);
}
```

```typescript
const EXTENSIONS: Record<string, string> = {
	'application/pdf': '.pdf',
	'image/png': '.png',
	'image/jpeg': '.jpg',
};

async function downloadFile(reportId: string, sectionId: string) {
	const path = `/care/v1/report/${reportId}/section/${sectionId}/file/get/document`;
	const link = await call<{ url: string }>('GET', path);
	// The link points to a file host, not to the API. Do not send your key to it.
	const res = await fetch(link.url);
	if (!res.ok) {
		exitWith(
			'The link did not work. Run this command again to get a new one.',
		);
	}
	const kind = (res.headers.get('content-type') ?? '').split(';')[0];
	const name = sectionId + (EXTENSIONS[kind] ?? '.bin');
	const bytes = Buffer.from(await res.arrayBuffer());
	writeFileSync(name, bytes);
	console.log(`Saved ${bytes.length} bytes to ${name}.`);
}
```

```java
static final Map<String, String> EXTENSIONS =
        Map.of("application/pdf", ".pdf", "image/png", ".png", "image/jpeg", ".jpg");

static void downloadFile(String reportId, String sectionId) throws IOException, InterruptedException {
    String path = "/care/v1/report/%s/section/%s/file/get/document".formatted(reportId, sectionId);
    JsonNode link = Nurishd.call("GET", path);
    // The link points to a file host, not to the API. Do not send your key to it.
    HttpRequest request = HttpRequest.newBuilder(URI.create(link.path("url").asText())).build();
    HttpResponse<byte[]> res =
            HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofByteArray());
    if (res.statusCode() != 200) {
        exitWith("The link did not work. Run this command again to get a new one.");
    }
    String kind = res.headers().firstValue("Content-Type").orElse("").split(";")[0];
    String name = sectionId + EXTENSIONS.getOrDefault(kind, ".bin");
    Files.write(Path.of(name), res.body());
    System.out.println("Saved " + res.body().length + " bytes to " + name + ".");
}
```

```text
python reports.py file report-0001 section-0002
Saved 15 bytes to section-0002.pdf.
```

## 6. Keep the report private

A report is health data. Show it only to the patient it belongs to, and to people your BAA allows. Do not log its contents or the file link. Log ids and the `request_id` instead.

## 7. Choose the command

The last part reads the command line and runs one command. It catches an error answer and prints the status, the `code` and the `request_id`, then a hint. Branch on `code`, never on the message.

```python
HINTS = {
    "scope_not_granted": "Your key lacks a scope, or your company has no signed BAA.",
    "test_mode_only": "This helper works with a Sandbox key only. Use a key that starts with nk-test-.",
    "booking_not_completable": "The booking was canceled or is already completed. Use a booking in status booked.",
    "connection_scope_not_granted": "The patient does not share reports. Connect the patient again and ask for care.reports.",
    "connection_not_active": "The patient revoked the connection. You can no longer read this patient's reports.",
    "not_found": "Nothing with this id is visible to your company. Check the id.",
}


def main():
    args = sys.argv[1:]
    try:
        if len(args) == 2 and args[0] == "complete":
            complete_booking(args[1])
        elif len(args) == 1 and args[0] == "events":
            list_events()
        elif args[:1] == ["list"] and len(args) in (1, 2):
            list_reports(args[1] if len(args) == 2 else None)
        elif len(args) == 2 and args[0] == "show":
            show_report(args[1])
        elif len(args) == 3 and args[0] == "file":
            download_file(args[1], args[2])
        else:
            print("Usage:")
            print("  python reports.py complete BOOKING_ID")
            print("  python reports.py events")
            print("  python reports.py list [BOOKING_ID]")
            print("  python reports.py show REPORT_ID")
            print("  python reports.py file REPORT_ID SECTION_ID")
    except NurishdError as error:
        print(f"The API answered {error.status} {error.code} (request {error.request_id}).")
        print(HINTS.get(error.code, "See the Errors page for this code."))
        sys.exit(1)
```

```javascript
const HINTS = {
	scope_not_granted:
		'Your key lacks a scope, or your company has no signed BAA.',
	test_mode_only:
		'This helper works with a Sandbox key only. Use a key that starts with nk-test-.',
	booking_not_completable:
		'The booking was canceled or is already completed. Use a booking in status booked.',
	connection_scope_not_granted:
		'The patient does not share reports. Connect the patient again and ask for care.reports.',
	connection_not_active:
		"The patient revoked the connection. You can no longer read this patient's reports.",
	not_found: 'Nothing with this id is visible to your company. Check the id.',
};

async function main() {
	const args = process.argv.slice(2);
	try {
		if (args.length === 2 && args[0] === 'complete') {
			await completeBooking(args[1]);
		} else if (args.length === 1 && args[0] === 'events') {
			await listEvents();
		} else if (args[0] === 'list' && args.length <= 2) {
			await listReports(args[1]);
		} else if (args.length === 2 && args[0] === 'show') {
			await showReport(args[1]);
		} else if (args.length === 3 && args[0] === 'file') {
			await downloadFile(args[1], args[2]);
		} else {
			console.log('Usage:');
			console.log('  node reports.js complete BOOKING_ID');
			console.log('  node reports.js events');
			console.log('  node reports.js list [BOOKING_ID]');
			console.log('  node reports.js show REPORT_ID');
			console.log('  node reports.js file REPORT_ID SECTION_ID');
		}
	} catch (error) {
		if (!(error instanceof NurishdError)) throw error;
		console.log(
			`The API answered ${error.status} ${error.code} (request ${error.requestId}).`,
		);
		console.log(HINTS[error.code] ?? 'See the Errors page for this code.');
		process.exit(1);
	}
}
```

```typescript
const HINTS: Record<string, string> = {
	scope_not_granted:
		'Your key lacks a scope, or your company has no signed BAA.',
	test_mode_only:
		'This helper works with a Sandbox key only. Use a key that starts with nk-test-.',
	booking_not_completable:
		'The booking was canceled or is already completed. Use a booking in status booked.',
	connection_scope_not_granted:
		'The patient does not share reports. Connect the patient again and ask for care.reports.',
	connection_not_active:
		"The patient revoked the connection. You can no longer read this patient's reports.",
	not_found: 'Nothing with this id is visible to your company. Check the id.',
};

async function main() {
	const args = process.argv.slice(2);
	try {
		if (args.length === 2 && args[0] === 'complete') {
			await completeBooking(args[1]);
		} else if (args.length === 1 && args[0] === 'events') {
			await listEvents();
		} else if (args[0] === 'list' && args.length <= 2) {
			await listReports(args[1]);
		} else if (args.length === 2 && args[0] === 'show') {
			await showReport(args[1]);
		} else if (args.length === 3 && args[0] === 'file') {
			await downloadFile(args[1], args[2]);
		} else {
			console.log('Usage:');
			console.log('  node reports.js complete BOOKING_ID');
			console.log('  node reports.js events');
			console.log('  node reports.js list [BOOKING_ID]');
			console.log('  node reports.js show REPORT_ID');
			console.log('  node reports.js file REPORT_ID SECTION_ID');
		}
	} catch (error) {
		if (!(error instanceof NurishdError)) throw error;
		console.log(
			`The API answered ${error.status} ${error.code} (request ${error.requestId}).`,
		);
		console.log(HINTS[error.code] ?? 'See the Errors page for this code.');
		process.exit(1);
	}
}
```

```java
static final Map<String, String> HINTS = Map.of(
        "scope_not_granted",
        "Your key lacks a scope, or your company has no signed BAA.",
        "test_mode_only",
        "This helper works with a Sandbox key only. Use a key that starts with nk-test-.",
        "booking_not_completable",
        "The booking was canceled or is already completed. Use a booking in status booked.",
        "connection_scope_not_granted",
        "The patient does not share reports. Connect the patient again and ask for care.reports.",
        "connection_not_active",
        "The patient revoked the connection. You can no longer read this patient's reports.",
        "not_found",
        "Nothing with this id is visible to your company. Check the id.");

public static void main(String[] args) throws IOException, InterruptedException {
    try {
        if (args.length == 2 && args[0].equals("complete")) {
            completeBooking(args[1]);
        } else if (args.length == 1 && args[0].equals("events")) {
            listEvents();
        } else if (args.length >= 1 && args.length <= 2 && args[0].equals("list")) {
            listReports(args.length == 2 ? args[1] : null);
        } else if (args.length == 2 && args[0].equals("show")) {
            showReport(args[1]);
        } else if (args.length == 3 && args[0].equals("file")) {
            downloadFile(args[1], args[2]);
        } else {
            System.out.println("Usage:");
            System.out.println("  complete BOOKING_ID");
            System.out.println("  events");
            System.out.println("  list [BOOKING_ID]");
            System.out.println("  show REPORT_ID");
            System.out.println("  file REPORT_ID SECTION_ID");
        }
    } catch (NurishdException error) {
        System.out.println("The API answered " + error.status + " " + error.code
                + " (request " + error.requestId + ").");
        System.out.println(HINTS.getOrDefault(error.code, "See the Errors page for this code."));
        System.exit(1);
    }
}
```

## The whole program

```python
# file: reports.py
import sys
from pathlib import Path

import requests

from nurishd import NurishdError, call

EXTENSIONS = {
    "application/pdf": ".pdf",
    "image/png": ".png",
    "image/jpeg": ".jpg",
}

HINTS = {
    "scope_not_granted": "Your key lacks a scope, or your company has no signed BAA.",
    "test_mode_only": "This helper works with a Sandbox key only. Use a key that starts with nk-test-.",
    "booking_not_completable": "The booking was canceled or is already completed. Use a booking in status booked.",
    "connection_scope_not_granted": "The patient does not share reports. Connect the patient again and ask for care.reports.",
    "connection_not_active": "The patient revoked the connection. You can no longer read this patient's reports.",
    "not_found": "Nothing with this id is visible to your company. Check the id.",
}


def complete_booking(booking_id):
    path = f"/developer/v1/test-helper/booking/{booking_id}/complete/document"
    done = call("POST", path)
    print(f"Booking {done['booking_id']} is now {done['status']}.")
    print(f"A sample report was signed: {done['report_id']}")


def list_events():
    answer = call(
        "GET",
        "/developer/v1/event/query/documents",
        params={"type": "report.signed", "size": 10},
    )
    if not answer["data"]:
        print("No report.signed event yet. Wait a few seconds and run it again.")
    for event in answer["data"]:
        data = event["data"]
        print(f"{event['created']}: report {data['id']} for booking {data.get('booking')}")


def list_reports(booking_id=None):
    params = {"booking": booking_id} if booking_id else {}
    answer = call("GET", "/care/v1/report/query/documents", params=params)
    if not answer["data"]:
        print("No signed report found.")
    for item in answer["data"]:
        print(f"{item['report_id']}: booking {item['booking_id']}, signed {item['signed_at']}")


def show_report(report_id):
    report = call("GET", f"/care/v1/report/{report_id}/get/document")
    name = report["specialist_snapshot"].get("full_name", "unknown")
    print(f"Report {report['report_id']}, signed {report['signed_at']} by {name}")
    for section in sorted(report["sections"], key=lambda s: s["section_order"]):
        print()
        print(f"== {section['section_name']} ({section['section_type']}) ==")
        if section.get("section_content"):
            print(section["section_content"])
        if section["has_file"]:
            print(f"A file is attached. Run: file {report_id} {section['section_id']}")


def download_file(report_id, section_id):
    path = f"/care/v1/report/{report_id}/section/{section_id}/file/get/document"
    link = call("GET", path)
    # The link points to a file host, not to the API. Do not send your key to it.
    res = requests.get(link["url"], timeout=30)
    if not res.ok:
        sys.exit("The link did not work. Run this command again to get a new one.")
    kind = res.headers.get("Content-Type", "").split(";")[0]
    name = section_id + EXTENSIONS.get(kind, ".bin")
    Path(name).write_bytes(res.content)
    print(f"Saved {len(res.content)} bytes to {name}.")


def main():
    args = sys.argv[1:]
    try:
        if len(args) == 2 and args[0] == "complete":
            complete_booking(args[1])
        elif len(args) == 1 and args[0] == "events":
            list_events()
        elif args[:1] == ["list"] and len(args) in (1, 2):
            list_reports(args[1] if len(args) == 2 else None)
        elif len(args) == 2 and args[0] == "show":
            show_report(args[1])
        elif len(args) == 3 and args[0] == "file":
            download_file(args[1], args[2])
        else:
            print("Usage:")
            print("  python reports.py complete BOOKING_ID")
            print("  python reports.py events")
            print("  python reports.py list [BOOKING_ID]")
            print("  python reports.py show REPORT_ID")
            print("  python reports.py file REPORT_ID SECTION_ID")
    except NurishdError as error:
        print(f"The API answered {error.status} {error.code} (request {error.request_id}).")
        print(HINTS.get(error.code, "See the Errors page for this code."))
        sys.exit(1)


main()
```

```javascript
// file: reports.js
import { writeFileSync } from 'node:fs';
import { NurishdError, call } from './nurishd.js';

const EXTENSIONS = {
	'application/pdf': '.pdf',
	'image/png': '.png',
	'image/jpeg': '.jpg',
};

const HINTS = {
	scope_not_granted:
		'Your key lacks a scope, or your company has no signed BAA.',
	test_mode_only:
		'This helper works with a Sandbox key only. Use a key that starts with nk-test-.',
	booking_not_completable:
		'The booking was canceled or is already completed. Use a booking in status booked.',
	connection_scope_not_granted:
		'The patient does not share reports. Connect the patient again and ask for care.reports.',
	connection_not_active:
		"The patient revoked the connection. You can no longer read this patient's reports.",
	not_found: 'Nothing with this id is visible to your company. Check the id.',
};

function exitWith(message) {
	console.log(message);
	process.exit(1);
}

async function completeBooking(bookingId) {
	const path = `/developer/v1/test-helper/booking/${bookingId}/complete/document`;
	const done = await call('POST', path);
	console.log(`Booking ${done.booking_id} is now ${done.status}.`);
	console.log(`A sample report was signed: ${done.report_id}`);
}

async function listEvents() {
	const answer = await call('GET', '/developer/v1/event/query/documents', {
		params: { type: 'report.signed', size: 10 },
	});
	if (answer.data.length === 0) {
		console.log(
			'No report.signed event yet. Wait a few seconds and run it again.',
		);
	}
	for (const event of answer.data) {
		console.log(
			`${event.created}: report ${event.data.id} for booking ${event.data.booking}`,
		);
	}
}

async function listReports(bookingId) {
	const params = bookingId ? { booking: bookingId } : {};
	const answer = await call('GET', '/care/v1/report/query/documents', {
		params,
	});
	if (answer.data.length === 0) console.log('No signed report found.');
	for (const item of answer.data) {
		console.log(
			`${item.report_id}: booking ${item.booking_id}, signed ${item.signed_at}`,
		);
	}
}

async function showReport(reportId) {
	const report = await call(
		'GET',
		`/care/v1/report/${reportId}/get/document`,
	);
	const name = report.specialist_snapshot.full_name ?? 'unknown';
	console.log(
		`Report ${report.report_id}, signed ${report.signed_at} by ${name}`,
	);
	const sections = [...report.sections].sort(
		(a, b) => a.section_order - b.section_order,
	);
	for (const section of sections) {
		console.log();
		console.log(`== ${section.section_name} (${section.section_type}) ==`);
		if (section.section_content) console.log(section.section_content);
		if (section.has_file) {
			console.log(
				`A file is attached. Run: file ${reportId} ${section.section_id}`,
			);
		}
	}
}

async function downloadFile(reportId, sectionId) {
	const path = `/care/v1/report/${reportId}/section/${sectionId}/file/get/document`;
	const link = await call('GET', path);
	// The link points to a file host, not to the API. Do not send your key to it.
	const res = await fetch(link.url);
	if (!res.ok) {
		exitWith(
			'The link did not work. Run this command again to get a new one.',
		);
	}
	const kind = (res.headers.get('content-type') ?? '').split(';')[0];
	const name = sectionId + (EXTENSIONS[kind] ?? '.bin');
	const bytes = Buffer.from(await res.arrayBuffer());
	writeFileSync(name, bytes);
	console.log(`Saved ${bytes.length} bytes to ${name}.`);
}

async function main() {
	const args = process.argv.slice(2);
	try {
		if (args.length === 2 && args[0] === 'complete') {
			await completeBooking(args[1]);
		} else if (args.length === 1 && args[0] === 'events') {
			await listEvents();
		} else if (args[0] === 'list' && args.length <= 2) {
			await listReports(args[1]);
		} else if (args.length === 2 && args[0] === 'show') {
			await showReport(args[1]);
		} else if (args.length === 3 && args[0] === 'file') {
			await downloadFile(args[1], args[2]);
		} else {
			console.log('Usage:');
			console.log('  node reports.js complete BOOKING_ID');
			console.log('  node reports.js events');
			console.log('  node reports.js list [BOOKING_ID]');
			console.log('  node reports.js show REPORT_ID');
			console.log('  node reports.js file REPORT_ID SECTION_ID');
		}
	} catch (error) {
		if (!(error instanceof NurishdError)) throw error;
		console.log(
			`The API answered ${error.status} ${error.code} (request ${error.requestId}).`,
		);
		console.log(HINTS[error.code] ?? 'See the Errors page for this code.');
		process.exit(1);
	}
}

await main();
```

```typescript
// file: reports.ts
import { writeFileSync } from 'node:fs';
import { NurishdError, call } from './nurishd.ts';
import type { Page } from './nurishd.ts';

interface Section {
	section_id: string;
	section_name: string;
	section_type: string;
	section_order: number;
	section_content?: string | null;
	has_file: boolean;
}

interface Report {
	report_id: string;
	signed_at: string;
	specialist_snapshot: { full_name?: string };
	sections: Section[];
}

interface ReportEvent {
	created: string;
	data: { id: string; booking?: string };
}

interface ReportItem {
	report_id: string;
	booking_id: string;
	signed_at: string;
}

const EXTENSIONS: Record<string, string> = {
	'application/pdf': '.pdf',
	'image/png': '.png',
	'image/jpeg': '.jpg',
};

const HINTS: Record<string, string> = {
	scope_not_granted:
		'Your key lacks a scope, or your company has no signed BAA.',
	test_mode_only:
		'This helper works with a Sandbox key only. Use a key that starts with nk-test-.',
	booking_not_completable:
		'The booking was canceled or is already completed. Use a booking in status booked.',
	connection_scope_not_granted:
		'The patient does not share reports. Connect the patient again and ask for care.reports.',
	connection_not_active:
		"The patient revoked the connection. You can no longer read this patient's reports.",
	not_found: 'Nothing with this id is visible to your company. Check the id.',
};

function exitWith(message: string): never {
	console.log(message);
	process.exit(1);
}

async function completeBooking(bookingId: string) {
	const path = `/developer/v1/test-helper/booking/${bookingId}/complete/document`;
	const done = await call<{
		booking_id: string;
		report_id: string;
		status: string;
	}>('POST', path);
	console.log(`Booking ${done.booking_id} is now ${done.status}.`);
	console.log(`A sample report was signed: ${done.report_id}`);
}

async function listEvents() {
	const answer = await call<Page<ReportEvent>>(
		'GET',
		'/developer/v1/event/query/documents',
		{ params: { type: 'report.signed', size: 10 } },
	);
	if (answer.data.length === 0) {
		console.log(
			'No report.signed event yet. Wait a few seconds and run it again.',
		);
	}
	for (const event of answer.data) {
		console.log(
			`${event.created}: report ${event.data.id} for booking ${event.data.booking}`,
		);
	}
}

async function listReports(bookingId?: string) {
	const params: Record<string, string> = bookingId
		? { booking: bookingId }
		: {};
	const answer = await call<Page<ReportItem>>(
		'GET',
		'/care/v1/report/query/documents',
		{ params },
	);
	if (answer.data.length === 0) console.log('No signed report found.');
	for (const item of answer.data) {
		console.log(
			`${item.report_id}: booking ${item.booking_id}, signed ${item.signed_at}`,
		);
	}
}

async function showReport(reportId: string) {
	const report = await call<Report>(
		'GET',
		`/care/v1/report/${reportId}/get/document`,
	);
	const name = report.specialist_snapshot.full_name ?? 'unknown';
	console.log(
		`Report ${report.report_id}, signed ${report.signed_at} by ${name}`,
	);
	const sections = [...report.sections].sort(
		(a, b) => a.section_order - b.section_order,
	);
	for (const section of sections) {
		console.log();
		console.log(`== ${section.section_name} (${section.section_type}) ==`);
		if (section.section_content) console.log(section.section_content);
		if (section.has_file) {
			console.log(
				`A file is attached. Run: file ${reportId} ${section.section_id}`,
			);
		}
	}
}

async function downloadFile(reportId: string, sectionId: string) {
	const path = `/care/v1/report/${reportId}/section/${sectionId}/file/get/document`;
	const link = await call<{ url: string }>('GET', path);
	// The link points to a file host, not to the API. Do not send your key to it.
	const res = await fetch(link.url);
	if (!res.ok) {
		exitWith(
			'The link did not work. Run this command again to get a new one.',
		);
	}
	const kind = (res.headers.get('content-type') ?? '').split(';')[0];
	const name = sectionId + (EXTENSIONS[kind] ?? '.bin');
	const bytes = Buffer.from(await res.arrayBuffer());
	writeFileSync(name, bytes);
	console.log(`Saved ${bytes.length} bytes to ${name}.`);
}

async function main() {
	const args = process.argv.slice(2);
	try {
		if (args.length === 2 && args[0] === 'complete') {
			await completeBooking(args[1]);
		} else if (args.length === 1 && args[0] === 'events') {
			await listEvents();
		} else if (args[0] === 'list' && args.length <= 2) {
			await listReports(args[1]);
		} else if (args.length === 2 && args[0] === 'show') {
			await showReport(args[1]);
		} else if (args.length === 3 && args[0] === 'file') {
			await downloadFile(args[1], args[2]);
		} else {
			console.log('Usage:');
			console.log('  node reports.js complete BOOKING_ID');
			console.log('  node reports.js events');
			console.log('  node reports.js list [BOOKING_ID]');
			console.log('  node reports.js show REPORT_ID');
			console.log('  node reports.js file REPORT_ID SECTION_ID');
		}
	} catch (error) {
		if (!(error instanceof NurishdError)) throw error;
		console.log(
			`The API answered ${error.status} ${error.code} (request ${error.requestId}).`,
		);
		console.log(HINTS[error.code] ?? 'See the Errors page for this code.');
		process.exit(1);
	}
}

await main();
```

```java
// file: src/main/java/tutorial/Reports.java
package tutorial;

import com.fasterxml.jackson.databind.JsonNode;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import tutorial.Nurishd.NurishdException;

public class Reports {
    static final Map<String, String> EXTENSIONS =
            Map.of("application/pdf", ".pdf", "image/png", ".png", "image/jpeg", ".jpg");

    static final Map<String, String> HINTS = Map.of(
            "scope_not_granted",
            "Your key lacks a scope, or your company has no signed BAA.",
            "test_mode_only",
            "This helper works with a Sandbox key only. Use a key that starts with nk-test-.",
            "booking_not_completable",
            "The booking was canceled or is already completed. Use a booking in status booked.",
            "connection_scope_not_granted",
            "The patient does not share reports. Connect the patient again and ask for care.reports.",
            "connection_not_active",
            "The patient revoked the connection. You can no longer read this patient's reports.",
            "not_found",
            "Nothing with this id is visible to your company. Check the id.");

    static void exitWith(String message) {
        System.out.println(message);
        System.exit(1);
    }

    static void completeBooking(String bookingId) {
        String path = "/developer/v1/test-helper/booking/%s/complete/document".formatted(bookingId);
        JsonNode done = Nurishd.call("POST", path);
        System.out.println("Booking " + done.path("booking_id").asText() + " is now "
                + done.path("status").asText() + ".");
        System.out.println("A sample report was signed: " + done.path("report_id").asText());
    }

    static void listEvents() {
        JsonNode answer = Nurishd.call(
                "GET",
                "/developer/v1/event/query/documents",
                Map.of("type", "report.signed", "size", 10),
                null);
        if (answer.path("data").isEmpty()) {
            System.out.println("No report.signed event yet. Wait a few seconds and run it again.");
        }
        for (JsonNode event : answer.path("data")) {
            System.out.println(event.path("created").asText() + ": report "
                    + event.path("data").path("id").asText() + " for booking "
                    + event.path("data").path("booking").asText());
        }
    }

    static void listReports(String bookingId) {
        Map<String, Object> params = bookingId == null ? Map.of() : Map.of("booking", bookingId);
        JsonNode answer = Nurishd.call("GET", "/care/v1/report/query/documents", params, null);
        if (answer.path("data").isEmpty()) {
            System.out.println("No signed report found.");
        }
        for (JsonNode item : answer.path("data")) {
            System.out.println(item.path("report_id").asText() + ": booking "
                    + item.path("booking_id").asText() + ", signed "
                    + item.path("signed_at").asText());
        }
    }

    static void showReport(String reportId) {
        JsonNode report = Nurishd.call("GET", "/care/v1/report/%s/get/document".formatted(reportId));
        String name = report.path("specialist_snapshot").path("full_name").asText("unknown");
        System.out.println("Report " + report.path("report_id").asText() + ", signed "
                + report.path("signed_at").asText() + " by " + name);
        List<JsonNode> sections = new ArrayList<>();
        report.path("sections").forEach(sections::add);
        sections.sort(Comparator.comparingInt(s -> s.path("section_order").asInt()));
        for (JsonNode section : sections) {
            System.out.println();
            System.out.println("== " + section.path("section_name").asText() + " ("
                    + section.path("section_type").asText() + ") ==");
            if (!section.path("section_content").asText("").isEmpty()) {
                System.out.println(section.path("section_content").asText());
            }
            if (section.path("has_file").asBoolean()) {
                System.out.println("A file is attached. Run: file " + reportId + " "
                        + section.path("section_id").asText());
            }
        }
    }

    static void downloadFile(String reportId, String sectionId) throws IOException, InterruptedException {
        String path = "/care/v1/report/%s/section/%s/file/get/document".formatted(reportId, sectionId);
        JsonNode link = Nurishd.call("GET", path);
        // The link points to a file host, not to the API. Do not send your key to it.
        HttpRequest request = HttpRequest.newBuilder(URI.create(link.path("url").asText())).build();
        HttpResponse<byte[]> res =
                HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofByteArray());
        if (res.statusCode() != 200) {
            exitWith("The link did not work. Run this command again to get a new one.");
        }
        String kind = res.headers().firstValue("Content-Type").orElse("").split(";")[0];
        String name = sectionId + EXTENSIONS.getOrDefault(kind, ".bin");
        Files.write(Path.of(name), res.body());
        System.out.println("Saved " + res.body().length + " bytes to " + name + ".");
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        try {
            if (args.length == 2 && args[0].equals("complete")) {
                completeBooking(args[1]);
            } else if (args.length == 1 && args[0].equals("events")) {
                listEvents();
            } else if (args.length >= 1 && args.length <= 2 && args[0].equals("list")) {
                listReports(args.length == 2 ? args[1] : null);
            } else if (args.length == 2 && args[0].equals("show")) {
                showReport(args[1]);
            } else if (args.length == 3 && args[0].equals("file")) {
                downloadFile(args[1], args[2]);
            } else {
                System.out.println("Usage:");
                System.out.println("  complete BOOKING_ID");
                System.out.println("  events");
                System.out.println("  list [BOOKING_ID]");
                System.out.println("  show REPORT_ID");
                System.out.println("  file REPORT_ID SECTION_ID");
            }
        } catch (NurishdException error) {
            System.out.println("The API answered " + error.status + " " + error.code
                    + " (request " + error.requestId + ").");
            System.out.println(HINTS.getOrDefault(error.code, "See the Errors page for this code."));
            System.exit(1);
        }
    }
}
```

## If something goes wrong

| What you see                       | Why                                                                                                                                                                                                                      | What to do                                                                                         |
| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------- |
| `403 scope_not_granted`            | The key lacks `report:read` (or `booking:write` for the helper), or no BAA.                                                                                                                                              | Use a key with the scopes. See [Scopes](/docs/concepts/scopes) and [BAA handling](/docs/care/baa). |
| `403 connection_scope_not_granted` | The patient did not allow `care.reports`.                                                                                                                                                                                | Create the patient again with a key that holds `report:read`. Send the new link.                   |
| `403 test_mode_only`               | You called the test helper with a Production key.                                                                                                                                                                        | Use a Sandbox key. Production has no helper.                                                       |
| `404 not_found`                    | The report does not exist, or the visit was booked by the patient or by another company. Also a section that was not shared or has no file. For the helper: the booking was not made by your company with a Sandbox key. | Check the id.                                                                                      |
| `409 connection_not_active`        | The patient revoked the connection.                                                                                                                                                                                      | You can no longer read this patient's reports. Connect the patient again.                          |
| `409 booking_not_completable`      | The booking was canceled or is already completed.                                                                                                                                                                        | Book another visit and complete that one.                                                          |
| `422 validation_error`             | A parameter is invalid, such as a `size` over 50.                                                                                                                                                                        | Fix the parameter.                                                                                 |
| An empty list                      | The report is not signed yet, or the patient's connection is no longer active.                                                                                                                                           | In the Sandbox, run `complete` first.                                                              |
| `The link did not work`            | The short-lived link expired.                                                                                                                                                                                            | Run the `file` command again. It asks for a new link.                                              |

## Next

- [Visit reports](/docs/care/reports): every field and error of the report routes.
- [Events](/docs/events/events): the `report.signed` event and the other types.
- [BAA handling](/docs/care/baa): what care data needs.
- [Receive order webhooks](/docs/tutorials/receive-order-webhooks): receive events on your server.
