> ## 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.

# Create Resource

> Create a new FHIR resource with server-assigned ID

Creates a new FHIR resource. The server assigns a unique ID and returns the created resource with metadata.

## Endpoint

```
POST /fhir/{resourceType}
```

<ParamField path="resourceType" type="string" required>
  The FHIR resource type (e.g., `Patient`, `Observation`, `Encounter`)
</ParamField>

## Headers

<ParamField header="Content-Type" type="string" required>
  Must be `application/fhir+json` or `application/fhir+xml`
</ParamField>

<ParamField header="Accept" type="string">
  Response format: `application/fhir+json` (default) or `application/fhir+xml`
</ParamField>

<ParamField header="Prefer" type="string">
  Response style:

  * `return=representation` (default) - Return full resource
  * `return=minimal` - Return headers only
  * `return=OperationOutcome` - Return OperationOutcome
</ParamField>

<ParamField header="If-None-Exist" type="string">
  Conditional create. Search parameters to check for existing resource.

  Example: `identifier=http://hospital.example/mrn|12345`
</ParamField>

## Request Body

<CodeGroup>
  ```json Patient Example theme={null}
  {
    "resourceType": "Patient",
    "name": [
      {
        "family": "Doe",
        "given": ["John"]
      }
    ],
    "gender": "male",
    "birthDate": "1990-01-01",
    "identifier": [
      {
        "system": "http://hospital.example/mrn",
        "value": "12345"
      }
    ]
  }
  ```

  ```json Observation Example theme={null}
  {
    "resourceType": "Observation",
    "status": "final",
    "code": {
      "coding": [
        {
          "system": "http://loinc.org",
          "code": "8867-4",
          "display": "Heart rate"
        }
      ]
    },
    "subject": {
      "reference": "Patient/123"
    },
    "valueQuantity": {
      "value": 72,
      "unit": "beats/minute",
      "system": "http://unitsofmeasure.org",
      "code": "/min"
    }
  }
  ```
</CodeGroup>

<Note>
  **ID in Body**: Any `id` field in the request body is ignored. The server always assigns IDs for `POST` requests. Use `PUT` if you need to specify the ID.
</Note>

## Response

### 201 Created

Resource created successfully. Returns the new resource with server-assigned metadata.

<ResponseField name="id" type="string" required>
  Server-assigned unique identifier (typically UUID)
</ResponseField>

<ResponseField name="meta.versionId" type="string" required>
  Version number (starts at "1")
</ResponseField>

<ResponseField name="meta.lastUpdated" type="string" required>
  ISO 8601 timestamp of creation
</ResponseField>

<ResponseExample>
  ```json Response theme={null}
  {
    "resourceType": "Patient",
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "meta": {
      "versionId": "1",
      "lastUpdated": "2026-01-12T10:30:00.000Z"
    },
    "name": [
      {
        "family": "Doe",
        "given": ["John"]
      }
    ],
    "gender": "male",
    "birthDate": "1990-01-01",
    "identifier": [
      {
        "system": "http://hospital.example/mrn",
        "value": "12345"
      }
    ]
  }
  ```

  **Headers:**

  ```
  HTTP/1.1 201 Created
  Location: /fhir/Patient/550e8400-e29b-41d4-a716-446655440000
  ETag: W/"1"
  Last-Modified: Mon, 12 Jan 2026 10:30:00 GMT
  Content-Type: application/fhir+json
  ```
</ResponseExample>

### 200 OK (Conditional Create - Existing Resource)

When using `If-None-Exist` and a matching resource already exists.

<ResponseExample>
  ```json Response theme={null}
  {
    "resourceType": "Patient",
    "id": "existing-patient-id",
    "meta": {
      "versionId": "3",
      "lastUpdated": "2026-01-10T08:15:00.000Z"
    },
    "name": [
      {
        "family": "Doe",
        "given": ["John"]
      }
    ],
    "identifier": [
      {
        "system": "http://hospital.example/mrn",
        "value": "12345"
      }
    ]
  }
  ```

  **Headers:**

  ```
  HTTP/1.1 200 OK
  Location: /fhir/Patient/existing-patient-id
  Content-Location: /fhir/Patient/existing-patient-id/_history/3
  ```
</ResponseExample>

### 400 Bad Request

Validation failed or malformed request.

<ResponseExample>
  ```json Validation Error theme={null}
  {
    "resourceType": "OperationOutcome",
    "issue": [
      {
        "severity": "error",
        "code": "required",
        "expression": ["Patient.name"],
        "diagnostics": "Patient.name is required (minimum cardinality: 1)"
      },
      {
        "severity": "error",
        "code": "invalid",
        "expression": ["Patient.birthDate"],
        "diagnostics": "Invalid date format: expected YYYY-MM-DD"
      }
    ]
  }
  ```
</ResponseExample>

### 412 Precondition Failed

Conditional create found multiple matching resources (ambiguous).

<ResponseExample>
  ```json Multiple Matches Error theme={null}
  {
    "resourceType": "OperationOutcome",
    "issue": [
      {
        "severity": "error",
        "code": "multiple-matches",
        "diagnostics": "Multiple resources match the If-None-Exist criteria. Cannot determine which to return."
      }
    ]
  }
  ```
</ResponseExample>

### 422 Unprocessable Entity

Resource violates business rules or profile constraints.

<ResponseExample>
  ```json Profile Violation theme={null}
  {
    "resourceType": "OperationOutcome",
    "issue": [
      {
        "severity": "error",
        "code": "business-rule",
        "diagnostics": "Patient must have at least one identifier in this profile"
      }
    ]
  }
  ```
</ResponseExample>

## Examples

<CodeGroup>
  ```bash cURL - Basic Create theme={null}
  curl -X POST "https://your-server.com/fhir/Patient" \
    -H "Content-Type: application/fhir+json" \
    -H "Accept: application/fhir+json" \
    -d '{
      "resourceType": "Patient",
      "name": [{"family": "Doe", "given": ["John"]}],
      "gender": "male",
      "birthDate": "1990-01-01"
    }'
  ```

  ```bash cURL - Conditional Create theme={null}
  curl -X POST "https://your-server.com/fhir/Patient" \
    -H "Content-Type: application/fhir+json" \
    -H "Accept: application/fhir+json" \
    -H "If-None-Exist: identifier=http://hospital.example/mrn|12345" \
    -d '{
      "resourceType": "Patient",
      "identifier": [{"system": "http://hospital.example/mrn", "value": "12345"}],
      "name": [{"family": "Doe", "given": ["John"]}]
    }'
  ```

  ```bash cURL - Minimal Response theme={null}
  curl -X POST "https://your-server.com/fhir/Patient" \
    -H "Content-Type: application/fhir+json" \
    -H "Prefer: return=minimal" \
    -d '{
      "resourceType": "Patient",
      "name": [{"family": "Doe", "given": ["John"]}]
    }'
  # Returns only headers (Location, ETag), no body
  ```

  ```python Python Example theme={null}
  import requests

  url = "https://your-server.com/fhir/Patient"
  headers = {
      "Content-Type": "application/fhir+json",
      "Accept": "application/fhir+json"
  }
  data = {
      "resourceType": "Patient",
      "name": [{"family": "Doe", "given": ["John"]}],
      "gender": "male",
      "birthDate": "1990-01-01"
  }

  response = requests.post(url, json=data, headers=headers)
  if response.status_code == 201:
      patient = response.json()
      print(f"Created Patient/{patient['id']}")
  ```

  ```javascript JavaScript Example theme={null}
  const response = await fetch('https://your-server.com/fhir/Patient', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/fhir+json',
      'Accept': 'application/fhir+json'
    },
    body: JSON.stringify({
      resourceType: 'Patient',
      name: [{ family: 'Doe', given: ['John'] }],
      gender: 'male',
      birthDate: '1990-01-01'
    })
  });

  if (response.status === 201) {
    const patient = await response.json();
    console.log(`Created Patient/${patient.id}`);
  }
  ```
</CodeGroup>

## See Also

<CardGroup cols={2}>
  <Card title="Update Resource" href="/api-reference/endpoint/update">
    Update with PUT (can create with custom ID)
  </Card>

  <Card title="Read Resource" href="/api-reference/endpoint/read">
    Retrieve created resource
  </Card>

  <Card title="Batch Create" href="/api-reference/batch/transaction">
    Create multiple resources in one request
  </Card>

  <Card title="Learn FHIR CRUD" href="/learn-fhir/crud">
    Understand FHIR's create operation
  </Card>
</CardGroup>


## OpenAPI

````yaml POST /{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:
  /{resourceType}:
    post:
      tags:
        - CRUD
      summary: Create Resource
      description: >-
        Create a new resource of the specified type. Supports conditional create
        using If-None-Exist header.
      operationId: createResource
      parameters:
        - $ref: '#/components/parameters/ResourceType'
      requestBody:
        required: true
        description: The FHIR resource to create
        content:
          application/fhir+json:
            schema:
              $ref: '#/components/schemas/Resource'
          application/fhir+xml:
            schema:
              $ref: '#/components/schemas/Resource'
      responses:
        '200':
          description: Resource already exists (conditional create)
          content:
            application/fhir+json:
              schema:
                $ref: '#/components/schemas/Resource'
        '201':
          description: Resource created
          headers:
            Location:
              description: URL of the created resource
              schema:
                type: string
            ETag:
              description: Version identifier
              schema:
                type: string
          content:
            application/fhir+json:
              schema:
                $ref: '#/components/schemas/Resource'
        '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
  schemas:
    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
    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
    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
    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
    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
    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
  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

````