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

# POST /patients

> Create a new patient record with health information

## Endpoint

```
POST https://api.mycura.org/api/cura/patients
```

## Request Body

<ParamField body="name" type="string">
  Patient's full name
</ParamField>

<ParamField body="phone_number" type="string">
  Patient's phone number in ANY format. Supports:

  * `+15551234567` (E.164 format)
  * `15551234567` (11-digit)
  * `5551234567` (10-digit)
  * `(555) 123-4567` (formatted)
  * Any other format - will be automatically normalized to 11-digit format
</ParamField>

<ParamField body="conditions" type="array">
  Array of medical conditions as strings (e.g., `["Hypertension", "Diabetes"]`)
</ParamField>

<ParamField body="medications" type="array">
  Array of current medications

  <Expandable title="Medication Object Structure">
    <ParamField body="name" type="string">Medication name</ParamField>
    <ParamField body="dosage" type="string">Dosage information (e.g., "10mg")</ParamField>
    <ParamField body="frequency" type="string">How often taken (e.g., "daily", "twice daily")</ParamField>
  </Expandable>
</ParamField>

<ParamField body="allergies" type="string">
  Known allergies (comma-separated or as a single string)
</ParamField>

<ParamField body="notes" type="array">
  Array of note objects for additional patient information
</ParamField>

<ParamField body="reminders_enabled" type="boolean">
  Whether medication reminders are enabled for this patient (default: `false`)
</ParamField>

<ParamField body="refill_info" type="object">
  Prescription refill information
</ParamField>

<ParamField body="join_status" type="string">
  How the patient joined the system (e.g., "WEB", "WHATSAPP", "API")
</ParamField>

## Response

<ResponseField name="success" type="boolean">
  Indicates if the patient was created successfully
</ResponseField>

<ResponseField name="patient" type="object">
  The created patient object with generated ID and timestamps

  <Expandable title="Patient Object Fields">
    <ResponseField name="id" type="string">Generated unique patient identifier (UUID)</ResponseField>
    <ResponseField name="name" type="string">Patient's full name</ResponseField>
    <ResponseField name="phone_number" type="string">Normalized phone number (11-digit format)</ResponseField>
    <ResponseField name="conditions" type="array">Array of medical conditions</ResponseField>
    <ResponseField name="medications" type="array">Array of current medications</ResponseField>
    <ResponseField name="allergies" type="string">Known allergies</ResponseField>
    <ResponseField name="notes" type="array">Additional notes</ResponseField>
    <ResponseField name="reminders_enabled" type="boolean">Whether reminders are enabled</ResponseField>
    <ResponseField name="refill_info" type="object">Prescription refill information</ResponseField>
    <ResponseField name="join_status" type="string">How patient joined</ResponseField>
    <ResponseField name="created_at" type="string">Timestamp when patient was created</ResponseField>
    <ResponseField name="updated_at" type="string">Timestamp when patient was last updated</ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="error" type="string">
  Error message if the request failed (only present when success is false)
</ResponseField>

## Examples

### Basic Patient Creation

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://api.mycura.org/api/cura/patients" \
    -H "Content-Type: application/json" \
    -H "X-API-Key: YOUR_API_KEY" \
    -d '{
      "name": "Jane Doe",
      "phone_number": "5551234567",
      "reminders_enabled": true
    }'
  ```

  ```javascript Node.js theme={null}
  const response = await fetch('https://api.mycura.org/api/cura/patients', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-Key': 'YOUR_API_KEY'
    },
    body: JSON.stringify({
      name: 'Jane Doe',
      phone_number: '5551234567',
      reminders_enabled: true
    })
  });

  const data = await response.json();
  console.log(data.patient);
  ```

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

  response = requests.post(
      'https://api.mycura.org/api/cura/patients',
      headers={
          'Content-Type': 'application/json',
          'X-API-Key': 'YOUR_API_KEY'
      },
      json={
          'name': 'Jane Doe',
          'phone_number': '5551234567',
          'reminders_enabled': True
      }
  )

  data = response.json()
  print(data['patient'])
  ```
</CodeGroup>

### Comprehensive Patient Creation

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://api.mycura.org/api/cura/patients" \
    -H "Content-Type: application/json" \
    -H "X-API-Key: YOUR_API_KEY" \
    -d '{
      "name": "Jane Doe",
      "phone_number": "(555) 123-4567",
      "conditions": ["Hypertension", "Type 2 Diabetes"],
      "allergies": "Penicillin",
      "medications": [
        {
          "name": "Lisinopril",
          "dosage": "10mg",
          "frequency": "daily"
        },
        {
          "name": "Metformin",
          "dosage": "500mg",
          "frequency": "twice daily"
        }
      ],
      "reminders_enabled": true
    }'
  ```

  ```javascript Node.js theme={null}
  const patientData = {
    name: 'Jane Doe',
    phone_number: '(555) 123-4567',
    conditions: ['Hypertension', 'Type 2 Diabetes'],
    allergies: 'Penicillin',
    medications: [
      {
        name: 'Lisinopril',
        dosage: '10mg',
        frequency: 'daily'
      },
      {
        name: 'Metformin',
        dosage: '500mg',
        frequency: 'twice daily'
      }
    ],
    reminders_enabled: true
  };

  const response = await fetch('https://api.mycura.org/api/cura/patients', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-Key': 'YOUR_API_KEY'
    },
    body: JSON.stringify(patientData)
  });

  const data = await response.json();
  console.log('Created patient:', data.patient);
  ```
</CodeGroup>

## Response Examples

### Success Response

```json theme={null}
{
  "success": true,
  "patient": {
    "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    "name": "Jane Doe",
    "phone_number": "15551234567",
    "conditions": [
      "Hypertension",
      "Type 2 Diabetes"
    ],
    "allergies": "Penicillin",
    "medications": [
      {
        "name": "Lisinopril",
        "dosage": "10mg",
        "frequency": "daily"
      },
      {
        "name": "Metformin",
        "dosage": "500mg",
        "frequency": "twice daily"
      }
    ],
    "notes": [],
    "reminders_enabled": true,
    "refill_info": null,
    "join_status": "API",
    "created_at": "2024-01-20T10:30:00Z",
    "updated_at": "2024-01-20T10:30:00Z"
  }
}
```

### Duplicate Patient Error (409)

```json theme={null}
{
  "error": "Patient with this phone number already exists",
  "patient": {
    "id": "existing-patient-uuid",
    "name": "Jane Doe",
    "phone_number": "15551234567"
  }
}
```

## Phone Number Handling

<Note>
  **Phone Number Flexibility**: The API accepts phone numbers in ANY format and automatically normalizes them.
</Note>

All these formats are accepted and normalized to `15551234567`:

* `+15551234567`
* `15551234567`
* `5551234567`
* `(555) 123-4567`
* `555-123-4567`
* `555.123.4567`

The system will:

1. Remove all non-digit characters
2. Add country code `1` if missing (for 10-digit numbers)
3. Store in normalized 11-digit format

## Duplicate Prevention

The API automatically prevents duplicate patients based on phone number. If you attempt to create a patient with a phone number that already exists (in any format), the API will:

* Return HTTP status code `409 Conflict`
* Include the existing patient data in the response
* Not create a new record

This works even if phone numbers are in different formats:

* Creating with `5551234567` after `+15551234567` → Duplicate detected
* Creating with `(555) 123-4567` after `15551234567` → Duplicate detected

## Use Cases

<AccordionGroup>
  <Accordion icon="user-plus" title="New Patient Registration">
    Create patient records during onboarding or registration:

    ```javascript theme={null}
    async function registerNewPatient(formData) {
      try {
        const response = await fetch('https://api.mycura.org/api/cura/patients', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-API-Key': apiKey
          },
          body: JSON.stringify({
            name: formData.fullName,
            phone_number: formData.phone,
            reminders_enabled: formData.wantsReminders
          })
        });
        
        const data = await response.json();
        
        if (response.status === 409) {
          // Patient already exists
          console.log('Patient already exists:', data.patient);
          return data.patient;
        }
        
        if (!data.success) {
          throw new Error(data.error);
        }
        
        // Store patient ID for future use
        localStorage.setItem('patientId', data.patient.id);
        return data.patient;
      } catch (error) {
        console.error('Registration failed:', error);
        throw error;
      }
    }
    ```
  </Accordion>

  <Accordion icon="sync" title="Integration Workflow">
    Create patients as part of a larger integration workflow:

    ```javascript theme={null}
    async function onboardPatient(patientInfo) {
      // 1. Create patient in Cura
      const response = await createPatient(patientInfo);
      const patient = response.patient;
      
      // 2. Immediately ask an onboarding question
      const welcomeResponse = await fetch('https://api.mycura.org/api/cura/chat', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-API-Key': apiKey
        },
        body: JSON.stringify({
          message: 'What should I know about managing my health conditions?',
          patientId: patient.id
        })
      });
      
      const chatData = await welcomeResponse.json();
      
      // 3. Return both patient and initial guidance
      return {
        patient,
        initialGuidance: chatData.response
      };
    }
    ```
  </Accordion>
</AccordionGroup>

## Best Practices

<AccordionGroup>
  <Accordion icon="shield-check" title="Data Privacy">
    * Only collect necessary patient information
    * Implement proper consent mechanisms
    * Follow healthcare data compliance requirements (HIPAA, etc.)
    * Use secure transmission (HTTPS)
  </Accordion>

  <Accordion icon="check-circle" title="Data Quality">
    * Validate data on the client side before submission
    * Phone numbers can be in any format - the API will normalize them
    * Provide clear error messages for validation failures
    * Handle 409 duplicate responses gracefully
  </Accordion>

  <Accordion icon="sync" title="Integration">
    * Store the returned patient ID for future API calls
    * Handle duplicate patient scenarios gracefully (409 status)
    * Implement retry logic for network failures
    * The API will mark patients created via API with `join_status: "API"`
  </Accordion>
</AccordionGroup>

## Error Codes

| Status Code | Error Message                                   | Description                                 |
| ----------- | ----------------------------------------------- | ------------------------------------------- |
| 400         | "Failed to create patient"                      | Required fields are missing or invalid      |
| 401         | "Unauthorized - Invalid API key"                | The provided API key is invalid             |
| 409         | "Patient with this phone number already exists" | Patient with same phone (any format) exists |
| 500         | "Failed to create patient"                      | An unexpected error occurred                |
