> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ferrum.thalamiq.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Compartment Search

> Search resources within a compartment

## Compartment Search

Search for resources within a specific compartment. Compartments group related resources together (e.g., all resources related to a specific patient).

<ParamField path="compartment_type" type="string" required>
  The compartment type (`Patient`, `Encounter`, `RelatedPerson`, `Practitioner`, `Device`)
</ParamField>

<ParamField path="compartment_id" type="string" required>
  The ID of the compartment resource
</ParamField>

<ParamField path="resource_type" type="string">
  Optional: Filter to a specific resource type within the compartment
</ParamField>

## Endpoint

```
GET /fhir/:compartment_type/:compartment_id/:resource_type
GET /fhir/:compartment_type/:compartment_id/_search
POST /fhir/:compartment_type/:compartment_id/_search
POST /fhir/:compartment_type/:compartment_id/:resource_type/_search
```

## Patient Compartment

Search all resources related to a specific patient:

<CodeGroup>
  ```bash cURL theme={null}
  curl "https://your-server.com/fhir/Patient/123/Observation?code=http://loinc.org|29463-7"
  ```

  ```bash HTTP theme={null}
  GET /fhir/Patient/123/Observation?code=http://loinc.org|29463-7 HTTP/1.1
  Host: your-server.com
  ```
</CodeGroup>

## Encounter Compartment

Search all resources related to a specific encounter:

```bash theme={null}
GET /fhir/Encounter/456/Observation
```

## All Resources in Compartment

Search all resource types in a compartment:

```bash theme={null}
GET /fhir/Patient/123/_search
```

Or using POST:

```json theme={null}
POST /fhir/Patient/123/_search
Content-Type: application/x-www-form-urlencoded

_type=Observation,MedicationRequest&_count=20
```

## Search Parameters

You can combine compartment search with type-specific search parameters:

```bash theme={null}
GET /fhir/Patient/123/Observation?code=http://loinc.org|29463-7&date=ge2024-01-01&_sort=-date
```

## Response

### Success (200 OK)

Returns a `Bundle` containing resources in the compartment:

```json theme={null}
{
  "resourceType": "Bundle",
  "type": "searchset",
  "total": 15,
  "entry": [
    {
      "fullUrl": "https://your-server.com/fhir/Observation/789",
      "resource": {
        "resourceType": "Observation",
        "id": "789",
        "subject": {
          "reference": "Patient/123"
        },
        ...
      }
    }
  ]
}
```

## Standard Compartments

### Patient Compartment

Includes resources that reference the patient:

* `Observation`
* `Condition`
* `Procedure`
* `MedicationRequest`
* `Encounter`
* `DiagnosticReport`
* And more...

### Encounter Compartment

Includes resources that reference the encounter:

* `Observation`
* `Procedure`
* `MedicationRequest`
* `DiagnosticReport`
* And more...

### RelatedPerson Compartment

Includes resources related to a related person.

### Practitioner Compartment

Includes resources related to a practitioner.

### Device Compartment

Includes resources related to a device.

## Examples

### All Observations for a Patient

```bash theme={null}
GET /fhir/Patient/123/Observation
```

### Observations with Specific Code

```bash theme={null}
GET /fhir/Patient/123/Observation?code=http://loinc.org|29463-7
```

### All Resources in Patient Compartment

```bash theme={null}
GET /fhir/Patient/123/_search
```

### Filtered Compartment Search

```bash theme={null}
GET /fhir/Patient/123/Observation?status=final&date=ge2024-01-01&_count=50
```

## Notes

* Compartment membership is determined by resource references
* Not all resources belong to compartments
* Compartment search is more efficient than filtering by reference
* Use compartment search when you know the compartment resource ID
* The compartment ID must exist for the search to work


## OpenAPI

````yaml GET /{compartmentType}/{compartmentId}/{resourceType}
openapi: 3.1.0
info:
  title: Ferrum API
  description: >-
    FHIR R4 RESTful API implementation. All endpoints are prefixed with `/fhir`
    and follow the FHIR specification.
  version: 1.0.0
  contact:
    name: Ferrum
    url: https://github.com/thalamiq/ferrum
  license:
    name: MIT
servers:
  - url: http://localhost:8080/fhir
    description: Local development server (default port 8080)
  - url: https://your-server.com/fhir
    description: Production server (replace with your actual server URL)
  - url: https://api.example.com/fhir
    description: Example production server
security:
  - bearerAuth: []
paths:
  /{compartmentType}/{compartmentId}/{resourceType}:
    get:
      tags:
        - Search
      summary: Compartment Search
      description: Search for resources within a compartment.
      operationId: searchCompartment
      parameters:
        - name: compartmentType
          in: path
          required: true
          description: The compartment type (Patient, Encounter, etc.)
          schema:
            type: string
        - name: compartmentId
          in: path
          required: true
          description: The compartment resource ID
          schema:
            type: string
        - $ref: '#/components/parameters/ResourceType'
        - $ref: '#/components/parameters/Count'
        - $ref: '#/components/parameters/Sort'
      responses:
        '200':
          description: Search results
          content:
            application/fhir+json:
              schema:
                $ref: '#/components/schemas/Bundle'
        '400':
          $ref: '#/components/responses/BadRequest'
components:
  parameters:
    ResourceType:
      name: resourceType
      in: path
      required: true
      description: The FHIR resource type (e.g., Patient, Observation, Encounter)
      schema:
        type: string
    Count:
      name: _count
      in: query
      description: Maximum number of results to return
      schema:
        type: integer
        minimum: 0
        default: 10
    Sort:
      name: _sort
      in: query
      description: Sort order (prefix with - for descending)
      schema:
        type: string
  schemas:
    Bundle:
      type: object
      description: A container for a collection of resources
      required:
        - resourceType
        - type
      properties:
        resourceType:
          type: string
          enum:
            - Bundle
          description: Resource type
        type:
          type: string
          enum:
            - document
            - message
            - transaction
            - transaction-response
            - batch
            - batch-response
            - history
            - searchset
            - collection
          description: Indicates the purpose of this bundle
        total:
          type: integer
          description: If search, the total number of matches
        link:
          type: array
          items:
            $ref: '#/components/schemas/BundleLink'
          description: Links related to this Bundle
        entry:
          type: array
          items:
            $ref: '#/components/schemas/BundleEntry'
          description: Entry in the bundle
    BundleLink:
      type: object
      description: A link to another resource
      properties:
        relation:
          type: string
          description: >-
            See
            http://www.iana.org/assignments/link-relations/link-relations.xhtml#link-relations-1
        url:
          type: string
          format: uri
          description: Reference details for the link
    BundleEntry:
      type: object
      description: An entry in a bundle resource
      properties:
        fullUrl:
          type: string
          format: uri
          description: URI for resource
        resource:
          $ref: '#/components/schemas/Resource'
        request:
          $ref: '#/components/schemas/BundleEntryRequest'
        response:
          $ref: '#/components/schemas/BundleEntryResponse'
    OperationOutcome:
      type: object
      description: >-
        A collection of error, warning or information messages that result from
        a system action
      required:
        - resourceType
      properties:
        resourceType:
          type: string
          enum:
            - OperationOutcome
          description: Resource type
        issue:
          type: array
          items:
            $ref: '#/components/schemas/OperationOutcomeIssue'
          description: A list of issues associated with the operation
    Resource:
      type: object
      description: A FHIR resource. All resources have resourceType, id, and meta fields.
      required:
        - resourceType
      properties:
        resourceType:
          type: string
          description: The type of resource
        id:
          type: string
          description: Logical id of this artifact
        meta:
          $ref: '#/components/schemas/Meta'
      additionalProperties: true
    BundleEntryRequest:
      type: object
      description: Additional information about how this entry should be processed
      properties:
        method:
          type: string
          enum:
            - GET
            - POST
            - PUT
            - PATCH
            - DELETE
          description: HTTP verb for the operation
        url:
          type: string
          description: URL for HTTP equivalent of this entry
    BundleEntryResponse:
      type: object
      description: Indicates the results of processing the corresponding 'request' entry
      properties:
        status:
          type: string
          description: Status response code
        location:
          type: string
          description: The location (if the operation returns a location)
        etag:
          type: string
          description: The etag for the resource (if relevant)
        lastModified:
          type: string
          format: date-time
          description: Server's date time modified
        outcome:
          $ref: '#/components/schemas/OperationOutcome'
    OperationOutcomeIssue:
      type: object
      description: An issue associated with the operation
      required:
        - severity
        - code
      properties:
        severity:
          type: string
          enum:
            - fatal
            - error
            - warning
            - information
          description: Severity of the issue
        code:
          type: string
          enum:
            - invalid
            - structure
            - required
            - value
            - invariant
            - security
            - login
            - unknown
            - expired
            - forbidden
            - suppressed
            - processing
            - not-supported
            - duplicate
            - multiple-matches
            - not-found
            - deleted
            - too-long
            - code-invalid
            - extension
            - too-costly
            - business-rule
            - conflict
            - transient
            - lock-error
            - no-store
            - exception
            - timeout
            - incomplete
            - throttled
            - informational
          description: Error or warning code
        details:
          $ref: '#/components/schemas/CodeableConcept'
        diagnostics:
          type: string
          description: Additional diagnostic information about the issue
        location:
          type: array
          items:
            type: string
          description: XPath or JSONPath expression describing the location of the issue
    Meta:
      type: object
      description: Metadata about a resource
      properties:
        versionId:
          type: string
          description: Version specific identifier
        lastUpdated:
          type: string
          format: date-time
          description: When the resource version last changed
        profile:
          type: array
          items:
            type: string
            format: uri
          description: Profiles this resource claims to conform to
        tag:
          type: array
          items:
            $ref: '#/components/schemas/Coding'
          description: Tags applied to this resource
        security:
          type: array
          items:
            $ref: '#/components/schemas/Coding'
          description: Security labels applied to this resource
    CodeableConcept:
      type: object
      description: >-
        A concept that may be defined by a formal reference to a terminology or
        ontology
      properties:
        coding:
          type: array
          items:
            $ref: '#/components/schemas/Coding'
        text:
          type: string
          description: Plain text representation of the concept
    Coding:
      type: object
      description: A reference to a code defined by a terminology system
      properties:
        system:
          type: string
          format: uri
          description: Identity of the terminology system
        version:
          type: string
          description: Version of the system - if relevant
        code:
          type: string
          description: Symbol in syntax defined by the system
        display:
          type: string
          description: Representation defined by the system
  responses:
    BadRequest:
      description: Bad request - validation error or invalid input
      content:
        application/fhir+json:
          schema:
            $ref: '#/components/schemas/OperationOutcome'
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: Bearer token authentication

````