# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
This site has an agentic ask interface you may use to query the documentation dynamically by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://api-docs.getflipturn.com/index.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

---

# Overview

The Flipturn API can be used to retrieve data from the Flipturn Platform for use in other systems including ticketing systems, data warehouses, or other analysis/dashboard tools.

The API lives at `https://api.getflipturn.com/api/`, and can only be accessed over a secure `https` connection.

## Getting started

Read about [how to get an API key](/authorization).

## Integration help

We're happy to work with you to advise on the best way to use the API to achieve your goals. Just reach out to <support@getflipturn.com> and our engineering team will get in touch.

## Feedback and requests

We believe that your data in Flipturn should always be accessible to you to use as you wish, and are open to requests to expose additional data types in the API.

Please contact <support@getflipturn.com> with any feedback, questions, or API feature requests.

## OCPI

Flipturn also supports [OCPI](https://evroaming.org/ocpi/) for integration with roaming partners. Please contact us at <support@getflipturn.com> if you would like to get access to the OCPI API.


# Authorization

## Getting an API key

To create an API key, your user account must have "Owner"-level access. Log into Flipturn at [cloud.getflipturn.com](https://cloud.getflipturn.com/), go to Manage in the top navigation, select "API Keys" from the sidebar, and then click the "Create API Key" button.

API keys can be configured with limited access, so you can provision a key with access to only a specific site or subset of chargers.

## Using the API key

Once you have an API key, it should be passed in the `Authorization` header of the request, like so:

```sh
# Shell
curl "https://api.getflipturn.com/api/charging-sessions" -H "Authorization: Bearer {api_key}"
```

```js
// JavaScript
fetch('https://api.getflipturn.com/api/charging-sessions', {
  method: 'GET',
  headers: {
    Authorization: `Bearer ${apiKey}`,
  },
});
```

The API returns data in JSON format, along with an appropriate HTTP response code.


# Sites

## GET /api/sites

Retrieve a list of an organization's sites, chargers, and ports, as well as their most recent status and details about any ongoing charging sessions.

This endpoint has no parameters, and returns all sites, chargers, and ports each time.

### Response

The JSON response will contain a `data` field, which represents a nested list of sites, chargers, and charging ports.

```ts
{
  data: {
    id: number;
    name: string;
    address: string | null;
    timezone: string; // IANA format
    organization: {
      id: number;
      name: string;
    },
    chargers: {
      id: number;
      name: string;
      manufacturer: string | null;
      model: string | null;
      serialNumber: string | null;
      firmwareVersion: string | null;
      latitude: number | null;
      longitude: number | null;
      externalId: string | null;
      ocppId: string | null;
      type: string; // One of: "DCFC", "Level 2"
      powerSharing: boolean; // true if the charger has more than one port (power-sharing enabled)

      // null if the charger has never connected to Flipturn
      connectionStatus: {
        status: string; // e.g. "Connected", "Disconnected"
        timestamp: string; // ISO 8601 format
      } | null;
      numberOfPorts: number;
      ports: {
        id: number;
        name: string;
        portNumber: number;
        maximumPowerKw: number | null;
        // CCS1, J1772, or NACS
        connectorType: string;
        // null if the port has never sent an OCPP status
        ocppStatus: {
          status: string; // e.g. "Available", "Charging", "Faulted"
          timestamp: string; // ISO 8601 format
          errorCode: string; // OCPP error code, e.g. "NoError", "ConnectorLockFailure"
          vendorErrorCode: string | null; // Vendor-specific error code
          info: string | null; // Additional error information
        } | null;

        // Information about any ongoing charging session -- will be null if no charging session is
        // currently happening on this charger
        currentChargingSession: {
          id: number;
          startTime: string; // ISO 8601 format
          socStartPercent: number | null;
          energyDeliveredKwh: number;
          ocppIdTag: string | null;
          ocppTransactionId: number | null;
          // Latest meter readings from the charging session
          latestReadings: {
            powerKw: {
              value: number;
              timestamp: string; // ISO 8601 format
            } | null;
            currentA: {
              value: number;
              timestamp: string; // ISO 8601 format
            } | null;
            socPercent: {
              value: number;
              timestamp: string; // ISO 8601 format
            } | null;
            voltage: {
              value: number;
              timestamp: string; // ISO 8601 format
            } | null;
          };
          vehicle: {
            id: number;
            make: string | null;
            model: string | null;
            name: string;
            vin: string | null;
          } | null;
          rfid: {
            id: number;
            name: string | null;
          } | null;
          customer: {
            name: string;
          } | null;
        } | null;
      }[];
    }[];
  }[];
}
```

### Example request and response

Request:

```sh
curl "https://api.getflipturn.com/api/sites" -H "Authorization: Bearer {api_key}"
```

Response:

```js
{
  "data": [{
    "id": 1,
    "name": "Site 1",
    "address": "1234 Fake St, Long Beach, CA 90802",
    "timezone": "America/Los_Angeles",
    "organization": {
      "name": "Flipturn Demo Organization",
      "id": 1
    },
    "chargers": [
      {
        "id": 1,
        "manufacturer": "ABB",
        "model": "Terra 184",
        "name": "Test Charger",
        "serialNumber": "1234-5678",
        "firmwareVersion": "1.5.4.4",
        "externalId": "STATION-001",
        "ocppId": "CHARGER-001",
        "type": "DCFC",
        "powerSharing": false,
        "connectionStatus": {
          "status": "Connected",
          "timestamp": "2025-01-01T12:00:00.000Z"
        },
        "numberOfPorts": 1,
        "ports": [
          {
            "id": 1,
            "maximumPowerKw": 180,
            "name": "Test Port",
            "portNumber": 1,
            "connectorType": "CCS1",
            "ocppStatus": {
              "status": "Available",
              "timestamp": "2025-01-01T12:00:00.000Z",
              "errorCode": "NoError",
              "vendorErrorCode": null,
              "info": null
            },
            "currentChargingSession": {
              "id": 123,
              "startTime": "2025-01-01T11:30:00.000Z",
              "socStartPercent": 20,
              "energyDeliveredKwh": 10.5,
              "ocppIdTag": "test-tag",
              "ocppTransactionId": 456,
              "latestReadings": {
                "powerKw": {
                  "value": 50,
                  "timestamp": "2025-01-01T11:45:00.000Z"
                },
                "currentA": {
                  "value": 100,
                  "timestamp": "2025-01-01T11:45:00.000Z"
                },
                "socPercent": {
                  "value": 35,
                  "timestamp": "2025-01-01T11:45:00.000Z"
                },
                "voltage": {
                  "value": 400,
                  "timestamp": "2025-01-01T11:45:00.000Z"
                }
              },
              "vehicle": {
                "id": 22541553,
                "make": "Make",
                "model": "Model",
                "name": "9876",
                "vin": "demo-vin-0"
              },
              "rfid": null,
              "customer": {
                "name": "Test Customer"
              }
            }
          }
        ]
      }
    ]
  }]
}
```


# Chargers

## GET /api/chargers/:id

Retrieve detailed information about a specific charger by its internal ID, including its ports, connection status, and any ongoing charging sessions.

### Parameters

* `id` (path parameter): The internal ID of the charger

### Response

The JSON response will contain a `data` field with the charger information.

```ts
{
  data: {
    id: number;
    name: string;
    manufacturer: string | null;
    model: string | null;
    serialNumber: string | null;
    firmwareVersion: string | null;
    latitude: number | null;
    longitude: number | null;
    externalId: string | null;
    ocppId: string | null;
    type: string; // One of: "DCFC", "Level 2"
    powerSharing: boolean; // true if the charger has more than one port (power-sharing enabled)

    // null if the charger has never connected to Flipturn
    connectionStatus: {
      status: string; // e.g. "Connected", "Disconnected"
      timestamp: string; // ISO 8601 format
    } | null;
    numberOfPorts: number;
    ports: {
      id: number;
      name: string;
      portNumber: number;
      maximumPowerKw: number | null;
      // CCS1, J1772, or NACS
      connectorType: string;
      // null if the port has never sent an OCPP status
      ocppStatus: {
        status: string; // e.g. "Available", "Charging", "Faulted"
        timestamp: string; // ISO 8601 format
        errorCode: string; // OCPP error code, e.g. "NoError", "ConnectorLockFailure"
        vendorErrorCode: string | null; // Vendor-specific error code
        info: string | null; // Additional error information
      } | null;

      // Information about any ongoing charging session -- will be null if no charging session is
      // currently happening on this port
      currentChargingSession: {
        id: number;
        startTime: string; // ISO 8601 format
        socStartPercent: number | null;
        energyDeliveredKwh: number;
        ocppIdTag: string | null;
        ocppTransactionId: number | null;
        // Latest meter readings from the charging session
        latestReadings: {
          powerKw: {
            value: number;
            timestamp: string; // ISO 8601 format
          } | null;
          currentA: {
            value: number;
            timestamp: string; // ISO 8601 format
          } | null;
          socPercent: {
            value: number;
            timestamp: string; // ISO 8601 format
          } | null;
          voltage: {
            value: number;
            timestamp: string; // ISO 8601 format
          } | null;
        };
        vehicle: {
          id: number;
          make: string | null;
          model: string | null;
          name: string | null;
          vin: string | null;
        } | null;
        rfid: {
          id: number;
          name: string;
        } | null;
        customer: {
          name: string;
        } | null;
      } | null;
    }[];
    site: {
      id: number;
      name: string;
      address: string | null;
      timezone: string; // IANA format
    };
    // The organization that owns the charger
    organization: {
      id: number;
      name: string;
    };
  };
}
```

### Example request and response

Request by internal ID:

```sh
curl "https://api.getflipturn.com/api/chargers/123" -H "Authorization: Bearer {api_key}"
```

Response:

```js
{
  "data": {
    "id": 123,
    "name": "Test Charger",
    "manufacturer": "ABB",
    "model": "Terra 184",
    "serialNumber": "1234-5678",
    "firmwareVersion": "1.5.4.4",
    "latitude": 33.7701,
    "longitude": -118.1937,
    "externalId": "STATION-001",
    "ocppId": "CHARGER-001",
    "type": "DCFC",
    "powerSharing": true,
    "connectionStatus": {
      "status": "Connected",
      "timestamp": "2025-01-01T12:00:00.000Z"
    },
    "numberOfPorts": 2,
    "ports": [
      {
        "id": 1,
        "name": "Port 1",
        "portNumber": 1,
        "maximumPowerKw": 180,
        "connectorType": "CCS1",
        "ocppStatus": {
          "status": "Available",
          "timestamp": "2025-01-01T12:00:00.000Z",
          "errorCode": "NoError",
          "vendorErrorCode": null,
          "info": null
        },
        "currentChargingSession": null
      },
      {
        "id": 2,
        "name": "Port 2",
        "portNumber": 2,
        "maximumPowerKw": 180,
        "connectorType": "CCS1",
        "ocppStatus": {
          "status": "Charging",
          "timestamp": "2025-01-01T11:45:00.000Z",
          "errorCode": "NoError",
          "vendorErrorCode": null,
          "info": null
        },
        "currentChargingSession": {
          "id": 456,
          "startTime": "2025-01-01T11:30:00.000Z",
          "socStartPercent": 20,
          "energyDeliveredKwh": 10.5,
          "ocppIdTag": "test-tag",
          "ocppTransactionId": 789,
          "latestReadings": {
            "powerKw": {
              "value": 50,
              "timestamp": "2025-01-01T11:45:00.000Z"
            },
            "currentA": {
              "value": 100,
              "timestamp": "2025-01-01T11:45:00.000Z"
            },
            "socPercent": {
              "value": 35,
              "timestamp": "2025-01-01T11:45:00.000Z"
            },
            "voltage": {
              "value": 400,
              "timestamp": "2025-01-01T11:45:00.000Z"
            }
          },
          "vehicle": {
            "id": 22541553,
            "make": "Tesla",
            "model": "Model 3",
            "name": "9876",
            "vin": "demo-vin-0"
          },
          "rfid": {
            "id": 1,
            "name": "Employee Card"
          },
          "customer": {
            "name": "Test Customer"
          }
        }
      }
    ],
    "site": {
      "id": 1,
      "name": "Site 1",
      "address": "1234 Fake St, Long Beach, CA 90802",
      "timezone": "America/Los_Angeles"
    },
    "organization": {
      "id": 1,
      "name": "Flipturn Demo Organization"
    }
  }
}
```

## GET /api/chargers/by-external-id/:id

Retrieve detailed information about a specific charger by its external ID (network station ID), including its ports, connection status, and any ongoing charging sessions.

### Parameters

* `id` (path parameter): The external ID (network station ID) of the charger

### Response

The JSON response will contain a `data` field with the charger information. The response structure is identical to the GET /api/chargers/:id endpoint.

### Example request

```sh
curl "https://api.getflipturn.com/api/chargers/by-external-id/STATION-001" -H "Authorization: Bearer {api_key}"
```

The response will be the same as for the `GET /api/chargers/:id` endpoint.

## GET /api/chargers/by-ocpp-id/:id

Retrieve detailed information about a specific charger by its OCPP identifier, including its ports, connection status, and any ongoing charging sessions.

### Parameters

* `id` (path parameter): The OCPP identifier of the charger

### Response

The JSON response will contain a `data` field with the charger information. The response structure is identical to the GET /api/chargers/:id endpoint.

### Example request

```sh
curl "https://api.getflipturn.com/api/chargers/by-ocpp-id/CHARGER-001" -H "Authorization: Bearer {api_key}"
```

The response will be the same as for the `GET /api/chargers/:id` endpoint.


# Charging Sessions

## GET /api/charging-sessions

Retrieve a list of charging sessions.

### Parameters

Parameters should be passed as query parameters on the URL.

* `startTimeAfter` - ISO 8601 date string to filter the list to only sessions started at or after this time
* `startTimeBefore` - ISO 8601 date string to filter the list to only sessions started before this time
* `endTimeAfter` - ISO 8601 date string to filter the list to only sessions ended at or after this time
* `endTimeBefore` - ISO 8601 date string to filter the list to only sessions ended before this time
* `nextPageCursor` - When the filters match more than one page of data, pass this paramter to fetch the next page
* `includeIntervals` - Returns additional data about the charging session: max demand for the entire session, along with statistics for each 15-minute charging interval. When this parameter is included, an individual api key is limited to 1 concurrent request at a time.
* `includeTouEnergy` - Returns energy usage grouped into time of use periods for each session
* `includeInProgressSessions` - Returns charging sessions that are in progress
* `siteIds` - Site IDs, which can be retrieved from the /sites endpoint, to filter for. To pass multiple site IDs, add them to the query parameters like this: `siteIds[]=101&siteIds[]=102`
* `chargerIds` - Charger IDs, which can be retrieved from the /sites endpoint, to filter for. To pass multiple site IDs, add them to the query parameters like this: `chargerIds[]=101&chargerIds[]=102`
* `customerIds` - Customer IDs to filter for. To pass multiple customer IDs, add them to the query parameters like this: `customerIds[]=101&customerIds[]=102`
* `customerNames` - Customer names to filter for. To pass multiple customer names, add them to the query parameters like this: `customerNames[]=Acme%20Corp&customerNames[]=Fleet%20Inc`
* `includeDecommissioned` - When set to `true`, includes sessions from decommissioned chargers. By default, sessions from decommissioned chargers are excluded. Note: the Flipturn UI includes sessions from decommissioned chargers by default, so totals shown in the UI may differ from the API unless this parameter is set.

### Response

The JSON response will contain a `data` field with a list of charging sessions matching the filters, and a `pagination` field containing pagination details.

```ts
{
  data: {
    id: number;
    startTime: string; // ISO 8601 format
    updatedAt: string; // ISO 8601 format
    socStartPercent: number | null;
    socEndPercent: number | null;
    maxDemandKw: number | null;
    ocppIdTag: string | null;
    tags: string[];
    chargingStartTime: string; // ISO 8601 format, see "Charging time fields" note below

    // The following fields are nullable on in progress charging sessions
    endTime: string | null; // ISO 8601 format
    durationSeconds: number | null;
    energyDeliveredKwh: number | null;
    averageDemandKw: number | null;
    chargingEndTime: string | null; // ISO 8601 format, see "Charging time fields" note below
    chargingDurationSeconds: number | null; // The duration in seconds between chargingStartTime and chargingEndTime, see "Charging time fields" note below

    // Only defined if includeIntervals=true and charging session is ended. Session statistics, grouped into 15-minute intervals.
    intervals: {
      id: string;
      intervalStartTime: string; // ISO 8601 format
      intervalEndTime: string; // ISO 8601 format
      socStartPercent: number | null;
      socEndPercent: number | null;
      energyDeliveredKwh: number;
      maxDemandKw: number;
      averageDemandKw: number;
    }[] | null;

    // Only defined if includeTouEnergy=true. Energy usage grouped into time-of-use period buckets.
    touEnergy: {
      timeOfUsePeriodName: string;
      energyKwh: number;
    }[] | null;

    site: {
      id: number;
      name: string;
      locationId: string | null; // A unique identification number for a site, provided by a utility
    };
    charger: {
      id: number;
      name: string;
      manufacturer: string | null;
      model: string | null;
      networkServiceProvider: string;
      chargerType: string;
      serialNumber: string | null;
      numberOfPorts: number;
      latitude: number | null;
      longitude: number | null;
      externalId: string | null;
      ocppId: string | null;
    };
    port: {
      id: number;
      name: string;
      portNumber: number;
      maximumPowerKw: number | null;
    };
    vehicle: {
      id: number;
      name: string | null;
      vin: string | null;
      make: string | null;
      model: string | null;
    } | null;
    rfid: {
      id: number;
      name: string | null;
    } | null;
    customer: {
      name: string
    } | null;
    organization: {
      id: number;
      name: string;
    };
    ocppTransactionId: number | null; // The ID reported from the charger to identify messages related to the charging session
  }[];
  pagination: {
    hasNextPage: boolean;
    nextPageCursor: string | null;
  };
};
```

### Example request and response

Request:

```sh
curl "https://api.getflipturn.com/api/charging-sessions?startTimeAfter=2023-03-24T01:18:05.000Z&includeIntervals=true" -H "Authorization: Bearer {api_key}"
```

Response:

```js
{
  "data": [
    {
      "id": 428177,
      "startTime": "2023-08-29T22:57:46.479Z",
      "endTime": "2023-08-30T01:00:07.321Z",
      "updatedAt": "2023-08-30T01:00:07.321Z",
      "durationSeconds": 7341,
      "chargingStartTime": "2023-08-29T22:57:46.479Z",
      "chargingEndTime": "2023-08-30T00:45:00.000Z",
      "chargingDurationSeconds": 6441,
      "socStartPercent": 14,
      "socEndPercent": 50,
      "energyDeliveredKwh": 78.775,
      "averageDemandKw": 10.0,
      "maxDemandKw": 12,
      "intervals": [...],
      "ocppIdTag": "demo-id-tag-0",
      "tags": ['ABC Trucking', 'XYZ Trucking'],
      "site": { "id": 13, "name": "Long Beach", "locationId": null },
      "charger": {
        "id": 53, "name": "Long Beach 1", "manufacturer": "ABB", "model": "AC Wall Box",
        "networkServiceProvider": "Flipturn", "chargerType": "DCFC", "numberOfPorts": 1,
        "serialNumber": "DEMO-NUMBER", "latitude": 1.0, "longitude": 1.0,
        "externalId": "STATION-001", "ocppId": "CHARGER-001"
      },
      "port": { "id": 650244, "name": "Port 1", "portNumber": 1, "maximumPowerKw": 180},
      "vehicle": {
        "id": 22541553,
        "make": "Make",
        "model": "Model",
        "name": "9876",
        "vin": "demo-vin-0"
      },
      "customer": {
        "name": "Electric Fleet Transportation"
      },
      "organization": {
        "id": 1,
        "name": "Fleet Management Corp"
      }
    }
  ],
  "pagination": {
    "hasNextPage": true,
    "nextPageCursor": "NDMyNDc2"
  }
}
```

#### Charging time fields

Some utility reporting programs require reporting not just the start/end of the session, but also the time during which energy was actually delivered. The following fields provide this information:

* `chargingStartTime` - The time when energy started being delivered
* `chargingEndTime` - The time when energy stopped being delivered
* `chargingDurationSeconds` - The duration during which energy was delivered, in seconds

## Synchronizing charging sessions into an external system

If your goal is to continuously import charging sessions into a system like a data warehouse, you may set up a recurring job to import any new charging sessions that are in Flipturn. It's important to ensure that you don't double insert any charging sessions or miss one.

We recommend splitting this into two phases:

* Backfill all historical sessions
* Poll for new sessions

### Backfill all historical sessions

In order to export all sessions, the first request to the charging sessions endpoint should have no filter parameters. Then, every subsequent request will take the `nextPageCursor` from the prior response and add that to the next request.

Assume the first request returned:

```js
{
  "data": [
    { // 20 items },
  ]
  "pagination": {
    "hasNextPage": true,
    "nextPageCursor": "NDMyNDc2"
  }
}
```

The second request should look like:

```
/api/charging-sessions?nextPageCursor=NDMyNDc2
```

Repeat this process until you receive a response where `pagination.hasNextPage` is false.

### Poll for new sessions

Once all the historical sessions have been exported, you can continually poll the API to fetch sessions that have completed since the last request. Each request, you should keep track of the latest `endTimestamp` you've seen so far, and pass that in to `endTimeAfter`:

```
/api/charging-sessions?endTimeAfter=2023-08-30T01:00:07.321Z
```

#### Avoiding double-inserting

Instead of keeping track of the latest `endTimestamp`, some users might prefer to generate an `endTimeAfter` relative to when they're sending the request. For example, if you poll for new sessions every 30s, each request could set `endTimeAfter` to a timestamp slightly more than 30s ago to account for clock skew.

However, one risk of this buffer is it's possible to see a session that you've already exported. To help deduplicate, each charging session has a unique `id`, so it's recommended to use this as a unique key to ensure you don't insert the same charging session twice.


# Charger Health

## GET /api/charger-health

Retrieve health, uptime, error, and utilization statistics for all chargers in an organization, grouped by charger and port, over a specified time interval. This endpoint is useful for generating reliability and performance reports for your charging infrastructure.

### Parameters

Parameters should be passed as query parameters on the URL.

* `startTimestamp` (optional) - ISO 8601 date string with optional timezone offset. Start of the interval to analyze. Defaults to 30 days before the current time if not provided.
* `endTimestamp` (optional) - ISO 8601 date string with optional timezone offset. End of the interval to analyze. Defaults to the current time if not provided. If a future date is provided, it will be capped at the current time.
* `siteIds` (optional) - Array of site IDs to filter for. To pass multiple site IDs, add them to the query parameters like this: `siteIds[]=101&siteIds[]=102`.
* `chargerIds` (optional) - Array of charger IDs to filter for. To pass multiple charger IDs, add them to the query parameters like this: `chargerIds[]=201&chargerIds[]=202`.

### Response

The JSON response contains a `summary` field with aggregate statistics for the interval, and a `data` field with per-charger and per-port statistics.

A few notes:

* `activeTimeInIntervalSeconds` may be less than the total interval if the charger was activated after the start of the interval -- for example, if you select the month of June but the charger first came online on June 15, all of the statistics will be based on the second half of the month (instead of starting out immediately for 50% downtime).
* Error counts are grouped by type: `endedEarly` (charging stopped before expected), `failedToStart` (charging could not begin), and `other` (miscellaneous or unknown errors).
* The uptime seconds for a charger are the sum of the uptime across the ports, so the uptime can be longer than the actual length of the interval. As an example, if you select 2 weeks of data for a 2-port charger, the total uptime could be 4 weeks if both ports were up the whole time.

```ts
{
  summary: {
    startTime: string; // ISO 8601 format
    endTime: string; // ISO 8601 format
    errorCounts: {
      endedEarly: number;
      failedToStart: number;
      other: number;
      total: number;
    }
    chargingSessionsCount: number;
    uptime: {
      faultedSeconds: number;
      availableSeconds: number;
      unavailableSeconds: number;
      uptimePercent: number;
    }
  }
  data: Array<{
    chargerId: number;
    serialNumber: string | null;
    name: string;
    manufacturer: string | null; // Charger manufacturer, or null if unknown
    activeTimeInIntervalSeconds: number; // May be less than the interval if charger was activated after start
    site: {
      id: number;
      name: string;
    };
    connectivity: {
      onlineSeconds: number;
      offlineSeconds: number;
      onlinePercent: number;
    };
    maintenance: {
      maintenanceSeconds: number;
      maintenancePercent: number;
    };
    uptime: {
      faultedSeconds: number;
      availableSeconds: number;
      unavailableSeconds: number;
      uptimePercent: number;
    };
    utilization: {
      chargingSessionSeconds: number;
      utilizationPercent: number;
    };
    errorCounts: {
      endedEarly: number;
      failedToStart: number;
      other: number;
      total: number;
    };
    chargingSessionsCount: number;
    reportUrl: string;
    ports: Array<{
      id: number;
      name: string;
      uptime: {
        faultedSeconds: number;
        availableSeconds: number;
        unavailableSeconds: number;
        uptimePercent: number;
      };
      utilization: {
        chargingSessionSeconds: number;
        utilizationPercent: number;
      };
      errorCounts: {
        endedEarly: number;
        failedToStart: number;
        other: number;
        total: number;
      };
      chargingSessionsCount: number;
    }>;
  }>;
}
```

### Example request and response

Request:

```sh
curl "https://api.getflipturn.com/api/charger-health?startTimestamp=2024-07-01T00:00:00.000Z&endTimestamp=2024-07-31T23:59:59.999Z" -H "Authorization: Bearer {api_key}"
```

Response:

```js
{
  "summary": {
    "startTime": "2024-07-01T00:00:00.000Z",
    "endTime": "2024-07-31T23:59:59.999Z",
    "errorCounts": {
      "endedEarly": 2,
      "failedToStart": 1,
      "other": 0,
      "total": 3
    },
    "chargingSessionsCount": 42,
    "uptime": {
      "faultedSeconds": 2400,
      "availableSeconds": 5180000,
      "unavailableSeconds": 16000,
      "uptimePercent": 99.5
    }
  },
  "data": [
    {
      "chargerId": 101,
      "serialNumber": "FT-CHARGER-0001",
      "name": "Main Charger",
      "manufacturer": "Example Manufacturer",
      "activeTimeInIntervalSeconds": 2678400,
      "site": {
        "id": 1,
        "name": "Site 1"
      },
      "connectivity": {
        "onlineSeconds": 2600000,
        "offlineSeconds": 78400,
        "onlinePercent": 97.1
      },
      "maintenance": {
        "maintenanceSeconds": 3600,
        "maintenancePercent": 0.13
      },
      "uptime": {
        "faultedSeconds": 1200,
        "availableSeconds": 2590000,
        "unavailableSeconds": 8000,
        "uptimePercent": 99.6
      },
      "utilization": {
        "chargingSessionSeconds": 120000,
        "utilizationPercent": 4.6
      },
      "errorCounts": {
        "endedEarly": 1,
        "failedToStart": 1,
        "other": 0,
        "total": 2
      },
      "chargingSessionsCount": 20,
      "reportUrl": "https://cloud.getflipturn.com/o/99/reports/charger-health/chargers/101",
      "ports": [
        {
          "id": 201,
          "name": "Port 1",
          "uptime": {
            "faultedSeconds": 600,
            "availableSeconds": 1295000,
            "unavailableSeconds": 4000,
            "uptimePercent": 99.7
          },
          "utilization": {
            "chargingSessionSeconds": 60000,
            "utilizationPercent": 4.6
          },
          "errorCounts": {
            "endedEarly": 1,
            "failedToStart": 0,
            "other": 0,
            "total": 1
          },
          "chargingSessionsCount": 10
        }
      ]
    }
  ]
}
```


# Access IDs

Access IDs include RFID cards or vehicles. When a charger identifies who is initiating a charging session, it sends us an ID tag. This ID can be from one of the following sources:

* RFID Card: A card that is scanned on the charger to authenticate the user before charging begins.
* Vehicle: The MAC ID of a vehicle that is directly plugged into the charger.

## GET /api/access-ids

Retrieve a list of all Access IDs.

### Response

The JSON response will contain a `data` field with a list of access ids, and a `pagination` field containing pagination details.

```ts
{
  data: {
    id: number;
    ocppIdTag: string;
    type: string; // RFID | Vehicle
    name: string;
    authorizationStatus: string; // Authorized | Revoked
    authorizedAt: string; // ISO 8601 format
    revokedAt: string | null; // ISO 8601 format or null. Set only if authorizationStatus is Revoked
    createdAt: string; // ISO 8601 format
    updatedAt: string; // ISO 8601 format
    // Only defined if the "type" is a vehicle:
    vehicle: {
      id: number;
      make: string | null;
      model: string | null;
      name: string;
      vin: string | null;
    } | null;
  }[];
  pagination: {
    hasNextPage: boolean;
    nextPageCursor: string | null;
  };
};
```

### Example request and response

Request:

```sh
curl "https://api.getflipturn.com/api/access-ids" -H "Authorization: Bearer {api_key}"
```

Response:

```js
{
  "data": [
    {
      "id": 123,
      "ocppIdTag": "id-tag-1",
      "type": "Vehicle",
      "name": "Vehicle 1",
      "authorizationStatus": "Authorized",
      "authorizedAt": "2024-08-02T19:13:28.897Z",
      "revokedAt": null,
      "createdAt": "2024-08-02T19:13:28.897Z",
      "updatedAt": "2024-08-08T21:29:51.795Z",
      "vehicle": {
        "id": 20,
        "make": "Tesla",
        "model": "Model 3",
        "name": "Demo Tesla",
        "vin": "demo-vin-1"
      }
    },
    {
      "id": 124,
      "ocppIdTag": "rfid-card-1",
      "type": "RFID",
      "name": "RFID Card 1",
      "authorizationStatus": "Authorized",
      "authorizedAt": "2024-08-27T15:11:37.080Z",
      "revokedAt": null,
      "createdAt": "2024-08-08T16:21:17.191Z",
      "updatedAt": "2024-08-28T19:39:35.378Z",
      "vehicle": null
    }
  ],
  "pagination": {
    "hasNextPage": true,
    "nextPageCursor": "NDMyNDc2"
  }
}
```

## GET /api/access-ids/{id}

Retrieve the details for a specific Access ID (RFID Card or Vehicle).

### Response

```ts
{
  accessId: {
    id: number;
    ocppIdTag: string;
    type: string; // RFID | Vehicle
    name: string;
    authorizationStatus: string; // Authorized | Revoked
    authorizedAt: string; // ISO 8601 format
    revokedAt: string | null; // ISO 8601 format or null. Set only if authorizationStatus is Revoked
    createdAt: string; // ISO 8601 format
    updatedAt: string; // ISO 8601 format
    vehicle: {
      id: number;
      make: string | null;
      model: string | null;
      name: string;
      vin: string | null;
    } | null;
    customer: {
      name: string
    } | null;
  }
};
```

### Example request and response

Request:

```sh
curl "https://api.getflipturn.com/api/access-ids/123" -H "Authorization: Bearer {api_key}"
```

Response:

```js
{
  "accessId": {
    "id": 123,
    "ocppIdTag": "id-tag-1",
    "type": "Vehicle",
    "name": "Vehicle 1",
    "authorizationStatus": "Authorized",
    "authorizedAt": "2024-08-02T19:13:28.897Z",
    "revokedAt": null,
    "createdAt": "2024-08-02T19:13:28.897Z",
    "updatedAt": "2024-08-08T21:29:51.795Z",
    "vehicle": {
      "id": 20,
      "make": "Tesla",
      "model": "Model 3",
      "name": "Demo Tesla",
      "vin": "demo-vin-1"
    },
    "customer": {
      "name": "Electric Fleet Transportation"
    }
  }
}
```

## POST /api/access-ids

Create a new access ID. An access ID can be of two types: RFID or Vehicle. When creating a vehicle access ID, you can either create a new vehicle by passing in the `vehicle` parameters, or associate the new access ID with an existing vehicle by passing a `vehicleId`.

A single vehicle can have multiple access IDs, which can be used to represent cases where:

1. A vehicle has multiple charging ports with different MAC IDs
2. A vehicle MAC ID has changed over time, and you wish to maintain the connection to old charging sessions

### Request Body

```ts
{
  accessId: {
    type: string; // RFID | Vehicle (required)
    name: string; // (required)
    ocppIdTag: string; // (required)
    authorizationStatus: string; // Authorized | Revoked (optional: defaults to Authorized)

    // For Vehicle type only, pass these to create a new vehicle (optional)
    vehicle?: {
      make: string; // (optional "type" param must be vehicle)
      model: string; // (optional "type" param must be vehicle)
      vin: string; // (optional "type" param must be vehicle)
    }

    // For Vehicle type only, pass a vehicleId to associate with an existing vehicle
    vehicleId?: number; // (optional)

    // Pass to associate with an existing Customer or create a new Customer. Creates a new customer
    // if no existing customer is found with the same name, case insensitive. (optional)
    customer?: {
      name: string;
    }
  }
}
```

### Response

```ts
{
  accessId: {
    id: number;
    ocppIdTag: string; // This value is normalized, and as such may not exactly match what was POSTed
    type: string; // RFID | Vehicle
    name: string;
    authorizationStatus: string; // Authorized | Revoked
    authorizedAt: string; // ISO 8601 format
    revokedAt: string | null; // ISO 8601 format or null. Set only if authorizationStatus is Revoked
    createdAt: string; // ISO 8601 format
    updatedAt: string; // ISO 8601 format
    vehicle: {
      id: number;
      make: string | null;
      model: string | null;
      name: string;
      vin: string | null;
    } | null;
    customer: {
      name: string;
    } | null;
  }
};
```

### Example request for vehicle and response

Request:

```sh
curl -X POST "https://api.getflipturn.com/api/access-ids" \
-H "Authorization: Bearer {api_key}" \
-H "Content-Type: application/json" \
-d '{
  "accessId": {
    "type": "Vehicle",
    "ocppIdTag": "test-ocpp-id-tag",
    "name": "Vehicle 1",
    "vehicle": {
      "vin": "demo-vehicle-vin",
      "make": "Tesla",
      "model": "Model 3"
    },
    "customer": {
      "name": "Electric Fleet Transportation"
    }
  }
}'
```

Response:

```js
{
  "accessId": {
    "id": 123,
    "ocppIdTag": "test-ocpp-id-tag",
    "type": "Vehicle",
    "name": "Vehicle 1",
    "authorizationStatus": "Authorized",
    "authorizedAt": "2024-08-02T19:13:28.897Z",
    "revokedAt": null,
    "createdAt": "2024-08-02T19:13:28.897Z",
    "updatedAt": "2024-08-08T21:29:51.795Z",
    "vehicle": {
      "id": 20,
      "make": "Tesla",
      "model": "Model 3",
      "name": "Vehicle 1",
      "vin": "demo-vehicle-vin"
    },
    "customer": {
      "name": "Electric Fleet Transportation"
    }
  }
}
```

### Example request for RFID card and response

Request:

```sh
curl -X POST "https://api.getflipturn.com/api/access-ids" \
-H "Authorization: Bearer {api_key}" \
-H "Content-Type: application/json" \
-d '{
  "accessId": {
    "type": "RFID",
    "ocppIdTag": "test-ocpp-id-tag",
    "name": "Card 1",
    "customer": {
      "name": "Electric Fleet Transportation"
    }
  }
}'
```

Response:

```js
{
  "accessId": {
    "id": 123,
    "ocppIdTag": "test-ocpp-id-tag",
    "type": "RFID",
    "name": "Card 1",
    "authorizationStatus": "Authorized",
    "authorizedAt": "2024-08-02T19:13:28.897Z",
    "revokedAt": null,
    "createdAt": "2024-08-02T19:13:28.897Z",
    "updatedAt": "2024-08-08T21:29:51.795Z",
    "vehicle": null,
    "customer": {
      "name": "Electric Fleet Transportation"
    }
  }
}
```

## PATCH /api/access-ids/{id}

Update an Access ID (RFID Card or Vehicle).

### Request Body

For optional fields, explicitly providing null will delete the value.

```ts
{
  accessId: {
    name: string;
    authorizationStatus: string; // Authorized | Revoked
    vehicle: {
      make: string;
      model: string;
      vin: string;
    },
    customer: {
      name: string;  // (creates a new customer if no existing customer is found with the same name, case insensitive)
    }
  }
}
```

### Response

```ts
{
  accessId: {
    id: number;
    ocppIdTag: string;
    type: string; // RFID | Vehicle
    name: string;
    authorizationStatus: string; // Authorized | Revoked
    authorizedAt: string; // ISO 8601 format
    revokedAt: string | null; // ISO 8601 format or null. Set only if authorizationStatus is Revoked
    createdAt: string; // ISO 8601 format
    updatedAt: string; // ISO 8601 format
    vehicle: {
      id: number;
      make: string | null;
      model: string | null;
      name: string;
      vin: string | null;
    } | null;
    customer: {
      name: string
    } | null;
  }
};
```

### Example request and response

Request:

```sh
curl -X PATCH "https://api.getflipturn.com/api/access-ids/321" \
-H "Authorization: Bearer {api_key}" \
-H "Content-Type: application/json" \
-d '{
  "accessId": {
    "name": "Decommissioned Vehicle",
    "authorizationStatus": "Revoked",
    "customer": {
      "name": "Electric Fleet Transportation"
    }
  }
}'
```

Response:

```js
{
  "accessId": {
    "id": 321,
    "ocppIdTag": "test-ocpp-id-tag",
    "type": "Vehicle",
    "name": "Decommissioned Vehicle",
    "authorizationStatus": "Revoked",
    "authorizedAt": "2024-08-02T19:13:28.897Z",
    "revokedAt": "2024-08-10T15:13:28.897Z",
    "createdAt": "2024-08-02T19:13:28.897Z",
    "updatedAt": "2024-08-10T15:13:28.897Z",
    "vehicle": {
      "id": 20,
      "make": "Tesla",
      "model": "Model 3",
      "name": "Vehicle 1",
      "vin": "demo-vehicle-vin"
    },
    "customer": {
      "name": "Electric Fleet Transportation"
    }
  }
}
```

## PUT /api/access-ids/batch

Create or update up to 1000 access IDs in a single request. This endpoint is designed for syncing an entire fleet of vehicles or RFID cards with Flipturn.

The endpoint matches existing access IDs by `ocppIdTag`. If a matching access ID exists, it is updated; otherwise, a new one is created.

Vehicles are matched by `name` (case-insensitive). If no vehicle with the name exists, one is created automatically. Multiple access IDs with the same `name` are grouped onto the same vehicle.

Access IDs not included in the request are not affected, so an access ID will never be deleted from this endpoint.

### Request Body

```ts
{
  accessIds: {
    ocppIdTag: string; // (required)
    name: string; // (required)
    type: string; // RFID | Vehicle (required)
    authorizationStatus?: string; // Authorized | Revoked (optional: defaults to Authorized for new items)

    // For Vehicle type only (optional). Providing this on an RFID-type item returns an error.
    vehicle?: {
      make?: string | null;
      model?: string | null;
      vin?: string | null;
    }

    // Associate with a customer. Creates a new customer if no existing customer
    // is found with the same name (case-insensitive). (optional)
    customer?: {
      name: string;
    }
  }[] // Maximum 1000 items per request
}
```

### Edge cases

* If multiple items in a single request share the same vehicle name but provide different vehicle details (make, model, vin), the first item's details are used for the vehicle.
* If a vehicle already has telematics data, the `vin` field from the request is ignored to avoid overwriting telematics-sourced VIN data.

### Response

Each item in the `results` array corresponds to the item at the same index in the request. Items that fail are returned with `outcome: "error"` and an `error` message; other items in the batch are still processed.

```ts
{
  results: {
    ocppIdTag: string; // Normalized ocppIdTag
    outcome: string; // created | updated | error
    accessId?: {
      id: number;
      ocppIdTag: string;
      type: string; // RFID | Vehicle
      name: string;
      authorizationStatus: string; // Authorized | Revoked
      authorizedAt: string; // ISO 8601 format
      revokedAt: string | null;
      createdAt: string; // ISO 8601 format
      updatedAt: string; // ISO 8601 format
      vehicle: {
        id: number;
        make: string | null;
        model: string | null;
        name: string;
        vin: string | null;
      } | null;
      customer: {
        name: string;
      } | null;
    }; // Present when outcome is "created" or "updated"
    error?: string; // Present when outcome is "error"
  }[]
}
```

### Example request with mixed Vehicle and RFID items

Request:

```sh
curl -X PUT "https://api.getflipturn.com/api/access-ids/batch" \
-H "Authorization: Bearer {api_key}" \
-H "Content-Type: application/json" \
-d '{
  "accessIds": [
    {
      "ocppIdTag": "mac-bus42-001",
      "name": "Bus 42",
      "type": "Vehicle",
      "vehicle": { "make": "Proterra", "model": "ZX5", "vin": "1PROTVIN0001" },
      "customer": { "name": "Metro Transit" }
    },
    {
      "ocppIdTag": "mac-bus42-002",
      "name": "Bus 42",
      "type": "Vehicle"
    },
    {
      "ocppIdTag": "rfid-badge-001",
      "name": "Driver Badge 1",
      "type": "RFID",
      "customer": { "name": "Metro Transit" }
    }
  ]
}'
```

Response:

```js
{
  "results": [
    {
      "ocppIdTag": "mac-bus42-001",
      "outcome": "created",
      "accessId": {
        "id": 500,
        "ocppIdTag": "mac-bus42-001",
        "type": "Vehicle",
        "name": "Bus 42",
        "authorizationStatus": "Authorized",
        "authorizedAt": "2025-03-17T17:00:00.000Z",
        "revokedAt": null,
        "createdAt": "2025-03-17T17:00:00.000Z",
        "updatedAt": "2025-03-17T17:00:00.000Z",
        "vehicle": {
          "id": 100,
          "make": "Proterra",
          "model": "ZX5",
          "name": "Bus 42",
          "vin": "1PROTVIN0001"
        },
        "customer": {
          "name": "Metro Transit"
        }
      }
    },
    {
      "ocppIdTag": "mac-bus42-002",
      "outcome": "created",
      "accessId": {
        "id": 501,
        "ocppIdTag": "mac-bus42-002",
        "type": "Vehicle",
        "name": "Bus 42",
        "authorizationStatus": "Authorized",
        "authorizedAt": "2025-03-17T17:00:00.000Z",
        "revokedAt": null,
        "createdAt": "2025-03-17T17:00:00.000Z",
        "updatedAt": "2025-03-17T17:00:00.000Z",
        "vehicle": {
          "id": 100,
          "make": "Proterra",
          "model": "ZX5",
          "name": "Bus 42",
          "vin": "1PROTVIN0001"
        },
        "customer": {
          "name": "Metro Transit"
        }
      }
    },
    {
      "ocppIdTag": "rfid-badge-001",
      "outcome": "created",
      "accessId": {
        "id": 502,
        "ocppIdTag": "rfid-badge-001",
        "type": "RFID",
        "name": "Driver Badge 1",
        "authorizationStatus": "Authorized",
        "authorizedAt": "2025-03-17T17:00:00.000Z",
        "revokedAt": null,
        "createdAt": "2025-03-17T17:00:00.000Z",
        "updatedAt": "2025-03-17T17:00:00.000Z",
        "vehicle": null,
        "customer": {
          "name": "Metro Transit"
        }
      }
    }
  ]
}
```


# Vehicles

Vehicles represent electric vehicles in the system. Each vehicle can have one or more access IDs (OCPP ID tags) associated with it, which can be used to represent cases where:

1. A vehicle has multiple charging ports with different MAC IDs
2. A vehicle MAC ID has changed over time, and you wish to maintain the connection to old charging sessions

Attaching an access ID to a vehicle can also be a way to associate an RFID card with the vehicle.

## GET /api/vehicles

Retrieve a list of all electric vehicles.

### Response

The JSON response will contain a `data` field with a list of vehicles, and a `pagination` field containing pagination details.

```ts
{
  data: {
    id: number;
    name: string | null;
    make: string | null;
    model: string | null;
    vin: string | null;
    licensePlate: string | null;
    hasTelematics: boolean;
    customer: {
      name: string;
    } | null;
    accessIds: {
      id: number;
      ocppIdTag: string;
      authorizationStatus: string; // Authorized | Revoked
    }[];
  }[];
  pagination: {
    hasNextPage: boolean;
    nextPageCursor: string | null;
  };
};
```

### Example request and response

Request:

```sh
curl "https://api.getflipturn.com/api/vehicles" -H "Authorization: Bearer {api_key}"
```

Response:

```js
{
  "data": [
    {
      "id": 20,
      "name": "Demo Tesla",
      "make": "Tesla",
      "model": "Model 3",
      "vin": "demo-vin-1",
      "licensePlate": "ABC123",
      "hasTelematics": false,
      "customer": {
        "name": "Electric Fleet Transportation"
      },
      "accessIds": [
        {
          "id": 123,
          "ocppIdTag": "id-tag-1",
          "authorizationStatus": "Authorized"
        }
      ]
    },
    {
      "id": 21,
      "name": "Vehicle 2",
      "make": null,
      "model": null,
      "vin": null,
      "licensePlate": null,
      "hasTelematics": false,
      "customer": null,
      "accessIds": []
    }
  ],
  "pagination": {
    "hasNextPage": false,
    "nextPageCursor": null
  }
}
```

## GET /api/vehicles/{id}

Retrieve the details for a specific vehicle.

### Response

```ts
{
  vehicle: {
    id: number;
    name: string | null;
    make: string | null;
    model: string | null;
    vin: string | null;
    licensePlate: string | null;
    hasTelematics: boolean;
    customer: {
      name: string;
    } | null;
    accessIds: {
      id: number;
      ocppIdTag: string;
      authorizationStatus: string; // Authorized | Revoked
    }[];
  }
};
```

### Example request and response

Request:

```sh
curl "https://api.getflipturn.com/api/vehicles/20" -H "Authorization: Bearer {api_key}"
```

Response:

```js
{
  "vehicle": {
    "id": 20,
    "name": "Demo Tesla",
    "make": "Tesla",
    "model": "Model 3",
    "vin": "demo-vin-1",
    "licensePlate": "ABC123",
    "hasTelematics": false,
    "customer": {
      "name": "Electric Fleet Transportation"
    },
    "accessIds": [
      {
        "id": 123,
        "ocppIdTag": "id-tag-1",
        "authorizationStatus": "Authorized"
      },
      {
        "id": 124,
        "ocppIdTag": "id-tag-2",
        "authorizationStatus": "Authorized"
      }
    ]
  }
}
```

## POST /api/vehicles

Create a new vehicle. When creating a vehicle, you can optionally associate one or more access IDs (OCPP ID tags) with it.

### Request Body

```ts
{
  vehicle: {
    name: string; // (required)
    make: string | null; // (optional)
    model: string | null; // (optional)
    vin: string | null; // (optional)
    licensePlate: string | null; // (optional)

    // (optional, creates a new customer if no existing customer is found with the same name, case insensitive)
    customer: {
      name: string;
    } | null;

    // (optional)
    accessIds: {
      ocppIdTag: string;
      authorizationStatus: string; // Authorized | Revoked (optional: defaults to Authorized)
    }[];
  }
}
```

### Response

```ts
{
  vehicle: {
    id: number;
    name: string | null;
    make: string | null;
    model: string | null;
    vin: string | null;
    licensePlate: string | null;
    hasTelematics: boolean;
    customer: {
      name: string;
    } | null;
    accessIds: {
      id: number;
      ocppIdTag: string;
      authorizationStatus: string; // Authorized | Revoked
    }[];
  }
};
```

### Example request and response

Request:

```sh
curl -X POST "https://api.getflipturn.com/api/vehicles" \
-H "Authorization: Bearer {api_key}" \
-H "Content-Type: application/json" \
-d '{
  "vehicle": {
    "name": "Vehicle 1",
    "make": "Tesla",
    "model": "Model 3",
    "vin": "demo-vehicle-vin",
    "licensePlate": "ABC123",
    "customer": {
      "name": "Electric Fleet Transportation"
    },
    "accessIds": [
      {
        "ocppIdTag": "ocpp-id-tag-1",
        "authorizationStatus": "Authorized"
      },
      {
        "ocppIdTag": "ocpp-id-tag-2",
        "authorizationStatus": "Revoked"
      }
    ]
  }
}'
```

Response:

```js
{
  "vehicle": {
    "id": 20,
    "name": "Vehicle 1",
    "make": "Tesla",
    "model": "Model 3",
    "vin": "demo-vehicle-vin",
    "licensePlate": "ABC123",
    "hasTelematics": false,
    "customer": {
      "name": "Electric Fleet Transportation"
    },
    "accessIds": [
      {
        "id": 123,
        "ocppIdTag": "ocpp-id-tag-1",
        "authorizationStatus": "Authorized"
      },
      {
        "id": 124,
        "ocppIdTag": "ocpp-id-tag-2",
        "authorizationStatus": "Revoked"
      }
    ]
  }
}
```

### Example request with minimal fields

Request:

```sh
curl -X POST "https://api.getflipturn.com/api/vehicles" \
-H "Authorization: Bearer {api_key}" \
-H "Content-Type: application/json" \
-d '{
  "vehicle": {
    "name": "Vehicle 1"
  }
}'
```

Response:

```js
{
  "vehicle": {
    "id": 20,
    "name": "Vehicle 1",
    "make": null,
    "model": null,
    "vin": null,
    "licensePlate": null,
    "hasTelematics": false,
    "customer": null,
    "accessIds": []
  }
}
```

## PATCH /api/vehicles/{id}

Update a vehicle.

### Request Body

For optional fields, explicitly providing `null` will delete the value. Omitting a field will leave it unchanged.

```ts
{
  vehicle: {
    name: string; // (optional)
    make: string | null; // (optional)
    model: string | null; // (optional)
    vin: string | null; // (optional)
    licensePlate: string | null; // (optional)
    customer: {
      name: string; // (optional, creates a new customer if no existing customer is found with the same name, case insensitive)
    } | null; // (optional, set to null to remove customer association)
  }
}
```

### Response

```ts
{
  vehicle: {
    id: number;
    name: string | null;
    make: string | null;
    model: string | null;
    vin: string | null;
    licensePlate: string | null;
    hasTelematics: boolean;
    customer: {
      name: string;
    } | null;
    accessIds: {
      id: number;
      ocppIdTag: string;
      authorizationStatus: string; // Authorized | Revoked
    }[];
  }
};
```

### Example request and response

Request:

```sh
curl -X PATCH "https://api.getflipturn.com/api/vehicles/20" \
-H "Authorization: Bearer {api_key}" \
-H "Content-Type: application/json" \
-d '{
  "vehicle": {
    "name": "Updated Vehicle Name",
    "make": "Toyota",
    "model": "Prius",
    "customer": {
      "name": "Electric Fleet Transportation"
    }
  }
}'
```

Response:

```js
{
  "vehicle": {
    "id": 20,
    "name": "Updated Vehicle Name",
    "make": "Toyota",
    "model": "Prius",
    "vin": "demo-vin-1",
    "licensePlate": "ABC123",
    "hasTelematics": false,
    "customer": {
      "name": "Electric Fleet Transportation"
    },
    "accessIds": [
      {
        "id": 123,
        "ocppIdTag": "id-tag-1",
        "authorizationStatus": "Authorized"
      }
    ]
  }
}
```

### Example request to remove fields

Request:

```sh
curl -X PATCH "https://api.getflipturn.com/api/vehicles/20" \
-H "Authorization: Bearer {api_key}" \
-H "Content-Type: application/json" \
-d '{
  "vehicle": {
    "name": "Updated Vehicle Name",
    "make": null,
    "model": null,
    "vin": null,
    "customer": null
  }
}'
```

Response:

```js
{
  "vehicle": {
    "id": 20,
    "name": "Updated Vehicle Name",
    "make": null,
    "model": null,
    "vin": null,
    "licensePlate": "ABC123",
    "hasTelematics": false,
    "customer": null,
    "accessIds": [
      {
        "id": 123,
        "ocppIdTag": "id-tag-1",
        "authorizationStatus": "Authorized"
      }
    ]
  }
}
```


# Alerts

## GET /api/alerts

Retrieve a list of all alerts.

### Parameters

Parameters should be passed as query parameters on the URL.

* `startTimestampAfter` - ISO 8601 date string to filter the list to only alerts sent after this time
* `alertRecipientIds` - Only query for alerts sent to specific recipient IDs. To find a recipient's ID, go to the Contact List page under Alerts and click "Edit" on the contact — the Contact ID is displayed at the bottom of the edit modal. To query for several recipient ids, use the same query parameter several times. For example, '\&alertRecipientIds=1\&alertRecipientIds=2\&alertRecipientIds=3' would query for alert recipients with IDs \[1, 2, 3].
* `includeMuted` - (Defaults to false) Filter out alerts that were not sent to users.
* `nextPageCursor` - When the filters match more than one page of data, pass this paramter to fetch the next page

### Response

The JSON response will contain a `data` field with a list of alerts matching the filters, and a `pagination` field containing pagination details.

```ts
{
  data: {
    id: number;
    type: 'lowBattery' | 'chargingCompleted' | 'chargingSessionError' | 'offlineCharger' | 'lateCharging';
    startTimestamp: string; // ISO 8601 format
    muted: boolean;
    // Alert-specific fields (only one will be populated depending on the alert type)
    lowBattery: {
      socThreshold: number | null;
      socPercent: number | null;
    } | null;
    chargingCompleted: {
      socThreshold: number | null;
      socPercent: number | null;
    } | null;
    chargingSessionError: {
      status: string | null; // Charger OCPP status -- available, etc
      ocppErrorCode: string | null;
      ocppVendorErrorCode: string | null;
      ocppInfo: string | null;
      errorContext: string | null; // Charging ended early, charging failed to start, etc
    } | null;
    offlineCharger: {
      thresholdMinutes: number | null;
    } | null;
    lateCharging: {
      originalEta: string | null; // ISO 8601 format
      currentEta: string | null; // ISO 8601 format
      originalDepartureTime: string | null; // ISO 8601 format
      currentDepartureTime: string | null; // ISO 8601 format
    } | null;
    // Additional optional details
    chargingSession: {
      id: number;
      startTime: string; // ISO 8601 format
      endTime: string | null; // ISO 8601 format
      durationSeconds: number | null;
      energyDeliveredKwh: number | null;
      socStartPercent: number | null;
      socEndPercent: number | null;
    } | null;
    site: {
      id: number;
      name: string;
      locationId: string | null;
    } | null;
    charger: {
      id: number;
      name: string;
      manufacturer: string | null;
      model: string | null;
      networkServiceProvider: string;
      chargerType: string;
      serialNumber: string | null;
      numberOfPorts: number;
      latitude: number | null;
      longitude: number | null;
      externalId: string | null;
      ocppId: string | null;
    } | null;
    port: {
      id: number;
      name: string;
      portNumber: number;
      maximumPowerKw: number | null;
    } | null;
    vehicle: {
      id: number;
      make: string | null;
      model: string | null;
      name: string | null;
      vin: string | null;
    } | null;
    organization: {
      id: number;
      name: string;
    } | null;
  }
  [];
}
```

### Example request and response

Request:

```sh
curl "https://api.getflipturn.com/api/alerts&alertRecipientIds=1&alertRecipientIds=2&startTimestampAfter=2024-04-30T01:00:07.321Z" -H "Authorization: Bearer {api_key}"
```

Response:

```js
{
  "data": [{
    "id": 123,
    "type": "lowBattery",
    "startTimestamp": "2024-04-30T01:00:07.321Z",
    "muted": false,
    "lowBattery": {
      "socThreshold": 20,
      "socPercent": 15
    },
    "chargingCompleted": null,
    "chargingSessionError": null,
    "offlineCharger": null,
    "lateCharging": null,
    "chargingSession": null,
    "site": {
      "id": 1,
      "name": "Site 1",
      "locationId": "LOC123"
    },
    "charger": {
      "id": 2,
      "name": "Main Charger",
      "manufacturer": "ABB",
      "model": "Terra 54",
      "networkServiceProvider": "Flipturn",
      "chargerType": "DCFC",
      "serialNumber": "SN123456",
      "numberOfPorts": 2,
      "latitude": 37.7749,
      "longitude": -122.4194,
      "externalId": "EXT123",
      "ocppId": "OCPP123"
    },
    "port": {
      "id": 3,
      "name": "Port A",
      "portNumber": 1,
      "maximumPowerKw": 50
    },
    "vehicle": {
      "id": 101,
      "make": "Proterra",
      "model": "ZX5",
      "name": "My Car",
      "vin": "VIN123456789"
    },
    "organization": {
      "id": 1,
      "name": "My Organization"
    }
  },
  // more items
  ],
  "pagination": {
    "hasNextPage": true,
    "nextPageCursor": "NDMyNDc2"
  }
}
```


# Errors

## GET /api/errors

Retrieve a list of charger errors. This is the same set of rows shown in the Charger errors report in the application.

Results are returned in reverse chronological order (most recent first) and are paginated with an opaque cursor (up to 2000 rows per page); see [Pagination and Error Handling](/pagination-and-errors) for details about the pagination approach.

### Parameters

Parameters should be passed as query parameters on the URL. For parameters that accept a list of IDs, pass the param multiple times, e.g. `&organizationIds=1&organizationIds=2`.

* `afterTimestamp` - ISO 8601 date string. Only return errors whose timestamp is greater than or equal to this time.
* `beforeTimestamp` - ISO 8601 date string. Only return errors whose timestamp is less than or equal to this time.
* `organizationIds` - Filter to organizations if using an API key that has access to multiple organizations.
* `siteIds` - Restrict to errors on chargers at these sites. Pass the parameter multiple times for multiple ids.
* `chargerIds` - Restrict to errors on these chargers. Pass the parameter multiple times for multiple ids.
* `nextPageCursor` - When the filters match more than one page of data, pass this value (returned in the previous response) to fetch the next page. Keep all other parameters the same as in the previous request.

### Response

The JSON response will contain a `data` field with a list of errors matching the filters, and a `pagination` field containing pagination details.

```ts
{
  data: {
    id: number; // charging port status id, stable across requests
    timestamp: string; // ISO 8601 format, when the error was reported by the charger
    ocppErrorCode: string; // Error code field from OCPP
    vendorErrorCode: string | null; // Vendor error code field from OCPP
    ocppInfo: string | null; // Info field from OCPP
    ocppStatus: string; // OCPP status the port was in when the error was reported (e.g. Faulted)
    
    // 'endedCharging' = error ended an in-progress session
    // 'preventedCharging' = error blocked a session from starting
    // 'muted' = error triggered an alert that was muted
    // 'other' = error did not fit any of the above buckets
    errorCategory: 'endedCharging' | 'preventedCharging' | 'muted' | 'other';
    // Linked charging session, only set if this error caused or occurred during a session
    chargingSession: {
      id: number;
      startTime: string; // ISO 8601 format
      endTime: string | null; // ISO 8601 format
      durationSeconds: number | null;
      energyDeliveredKwh: number | null;
      socStartPercent: number | null; // State of charge at start of session, if reported
      socEndPercent: number | null; // State of charge at end of session, if reported
    } | null;
    site: {
      id: number;
      name: string;
      locationId: string | null;
    } | null;
    charger: {
      id: number;
      name: string;
      manufacturer: string | null;
      model: string | null;
      networkServiceProvider: string;
      chargerType: string;
      serialNumber: string | null;
      numberOfPorts: number;
      latitude: number | null;
      longitude: number | null;
      externalId: string | null;
      ocppId: string | null;
    } | null;
    port: {
      id: number;
      name: string;
      portNumber: number;
      maximumPowerKw: number | null;
    } | null;
    organization: {
      id: number;
      name: string;
    } | null;
  }[];
  pagination: {
    hasNextPage: boolean;
    nextPageCursor: string | null;
  };
}
```

### Example request and response

Request:

```sh
curl "https://api.getflipturn.com/api/errors?afterTimestamp=2024-04-30T01:00:07.321Z" -H "Authorization: Bearer {token}"
```

Response:

```js
{
  "data": [{
    "id": 4567,
    "timestamp": "2024-04-30T18:23:11.000Z",
    "ocppErrorCode": "GroundFailure",
    "vendorErrorCode": "0x10",
    "ocppInfo": "Ground fault detected on connector 1",
    "ocppStatus": "Faulted",
    "errorCategory": "endedCharging",
    "chargingSession": {
      "id": 1234,
      "startTime": "2024-04-30T18:00:00.000Z",
      "endTime": "2024-04-30T18:23:11.000Z",
      "durationSeconds": 1391,
      "energyDeliveredKwh": 12.4,
      "socStartPercent": 30,
      "socEndPercent": 80
    },
    "site": {
      "id": 1,
      "name": "Site 1",
      "locationId": "LOC123"
    },
    "charger": {
      "id": 2,
      "name": "Main Charger",
      "manufacturer": "ABB",
      "model": "Terra 54",
      "networkServiceProvider": "Flipturn",
      "chargerType": "DCFC",
      "serialNumber": "SN123456",
      "numberOfPorts": 2,
      "latitude": 37.7749,
      "longitude": -122.4194,
      "externalId": "EXT123",
      "ocppId": "OCPP123"
    },
    "port": {
      "id": 3,
      "name": "Port A",
      "portNumber": 1,
      "maximumPowerKw": 50
    },
    "organization": {
      "id": 1,
      "name": "My Organization"
    }
  }
  // more items
  ],
  "pagination": {
    "hasNextPage": true,
    "nextPageCursor": "NDMyNDc2"
  }
}
```


# OCPP Messages

## GET /api/ocpp-messages

Retrieve a list of OCPP (Open Charge Point Protocol) messages for a specific charger.

### Parameters

Parameters should be passed as query parameters on the URL.

* `chargerId` - **Required** The ID of the charger to retrieve messages for
* `startTimestamp` - ISO 8601 date string to filter to messages created after this time (defaults to 24 hours ago)
* `endTimestamp` - ISO 8601 date string to filter to messages created before this time (defaults to current time)
* `messageType` - Filter messages by message type. Can be a single message type (e.g., `messageType=Authorize`) or multiple message types (e.g., `messageType[]=StartTransaction&messageType[]=StopTransaction`).
* `limit` - Maximum number of messages to return per page (defaults to 50, maximum 500). This is a page size, not a cap on the total number of messages you can retrieve — paginate with `nextPageCursor` to fetch more.
* `nextPageCursor` - When the filters match more than one page of data, pass this parameter to fetch the next page. See [Pagination and Error Handling](/pagination-and-errors) for details on how pagination works.

The date range must be less than 8 days long. If you need more than 8 days of OCPP messages, please make multiple API requests.

### Response

Messages will be sorted with the newest first, so that by default when you call the endpoint you get the latest messages.

The JSON response will contain a `data` field with a list of OCPP messages matching the filters, and a `pagination` field containing pagination details.

```ts
{
  data: {
    id: number;
    createdAt: string; // ISO 8601 format
    ocppChargerIdentity: string;
    messageType: string; // OCPP message type (e.g., 'Authorize', 'StartTransaction', 'GetConfiguration')
    messagePayload: any; // The original OCPP message payload
    messageResponse: any; // The OCPP response or error message
    chargerId: number;
    protocol: string; // OCPP protocol version ('ocpp1.6' or 'ocpp2.0.1')
  }
  [];
  pagination: {
    hasNextPage: boolean;
    nextPageCursor: string | null;
  }
}
```

### Example request and response

Request:

```sh
curl "https://api.getflipturn.com/api/ocpp-messages?chargerId=123&startTimestamp=2024-04-30T01:00:07.321Z" -H "Authorization: Bearer {api_key}"
```

Filtering by a single message type:

```sh
curl "https://api.getflipturn.com/api/ocpp-messages?chargerId=123&messageType=Authorize" -H "Authorization: Bearer {api_key}"
```

Filtering by multiple message types:

```sh
curl "https://api.getflipturn.com/api/ocpp-messages?chargerId=123&messageType[]=StartTransaction&messageType[]=StopTransaction" -H "Authorization: Bearer {api_key}"
```

Response:

```js
{
  "data": [  {
    "id": 456,
    "createdAt": "2024-04-30T01:00:07.321Z",
    "ocppChargerIdentity": "test-charger-1",
    "messageType": "Authorize",
    "messagePayload": {
      "idTag": "test-tag-1"
    },
    "messageResponse": {
      "idTagInfo": {
        "status": "Accepted"
      }
    },
    "chargerId": 123,
    "protocol": "ocpp1.6"
  },
  {
    "id": 457,
    "createdAt": "2024-04-30T01:05:12.456Z",
    "ocppChargerIdentity": "test-charger-1",
    "messageType": "StartTransaction",
    "messagePayload": {
      "connectorId": 1
    },
    "messageResponse": {
      "transactionId": 12345
    },
    "chargerId": 123,
    "protocol": "ocpp1.6"
  }],
  "pagination": {
    "hasNextPage": false,
    "nextPageCursor": null
  }
}
```

### Message responses in case of error

Generally, both the request and response for each message is a JSON object. However, in special cases, the response can be a string only. For example:

* `FlipturnRequestTimeout` is used as the response if the request to the charger timed out
* `NotSupported` is used as the response if the charger or server doesn't support this message type

### Streaming export to Google Pub/Sub or Kafka

In addition to the REST API above, Flipturn supports exporting OCPP messages in real time to Google Pub/Sub or Apache Kafka. If you need a streaming integration, please reach out to us at <support@getflipturn.com> and we'll help you get set up.


# Reservations

Reserve a charging port for a specific user (identified by an RFID tag or other token) so that the connector is blocked for all other users until the reservation expires or is cancelled.

Reservations use the OCPP `ReserveNow` and `CancelReservation` messages under the hood. Both OCPP 1.6 and OCPP 2.0.1 chargers are supported. The charger must support the Reservation profile; if it doesn't, the request will be rejected.

## POST /api/ocpp/reservations

Reserves a charging port. The reservation is active immediately and expires at `expiryDate`. Only the user with the matching `idTag` (or `parentIdTag` group) can start a session on the reserved connector.

### Request body

```ts
{
  portId: number;        // Flipturn charging port ID
  expiryDate: string;    // ISO 8601 datetime when the reservation expires
  idTag: string;         // Identifier of the user (RFID UID, token, etc). Max 20 characters.
  reservationId: number; // Unique integer identifier for this reservation (caller-assigned)
  parentIdTag?: string;  // Optional parent identifier for group reservations (OCPP 1.6 only)
  idTokenType?: string;  // Optional. OCPP 2.0.1 only. See below for valid values. Defaults to 'Central'.
}
```

**`idTokenType` values (OCPP 2.0.1 only):**

| Value        | Description                      |
| ------------ | -------------------------------- |
| `Central`    | Server-side identifier (default) |
| `eMAID`      | E-Mobility Account Identifier    |
| `ISO14443`   | RFID tag (ISO 14443)             |
| `ISO15693`   | RFID tag (ISO 15693)             |
| `KeyCode`    | Key code / PIN                   |
| `Local`      | Locally known identifier         |
| `MacAddress` | MAC address                      |

This field is ignored for OCPP 1.6 chargers.

### Response

```ts
{
  data: {
    status: 'Accepted' | 'Faulted' | 'Occupied' | 'Rejected' | 'Unavailable';
  }
}
```

| Status        | Meaning                                                                |
| ------------- | ---------------------------------------------------------------------- |
| `Accepted`    | Reservation has been made successfully                                 |
| `Faulted`     | The connector is faulted and cannot be reserved                        |
| `Occupied`    | The connector is currently in use                                      |
| `Rejected`    | The charger rejected the reservation (e.g. reservations not supported) |
| `Unavailable` | The connector is unavailable                                           |

### Example

**Request:**

```sh
curl -X POST "https://api.getflipturn.com/api/ocpp/reservations" \
  -H "Authorization: Bearer {api_key}" \
  -H "Content-Type: application/json" \
  -d '{
    "portId": 34,
    "expiryDate": "2026-04-01T14:00:00.000Z",
    "idTag": "RFID001",
    "reservationId": 1001
  }'
```

**Response:**

```json
{
  "data": {
    "status": "Accepted"
  }
}
```

## POST /api/ocpp/reservations/cancel

Cancels an active reservation on a charger.

### Request body

```ts
{
  chargerId: number;     // Flipturn charger ID
  reservationId: number; // The reservation ID that was used when creating the reservation
}
```

### Response

```ts
{
  data: {
    status: 'Accepted' | 'Rejected';
  }
}
```

| Status     | Meaning                                                            |
| ---------- | ------------------------------------------------------------------ |
| `Accepted` | Reservation was successfully cancelled                             |
| `Rejected` | The charger rejected the cancellation (e.g. reservation not found) |

### Example

**Request:**

```sh
curl -X POST "https://api.getflipturn.com/api/ocpp/reservations/cancel" \
  -H "Authorization: Bearer {api_key}" \
  -H "Content-Type: application/json" \
  -d '{
    "chargerId": 12,
    "reservationId": 1001
  }'
```

**Response:**

```json
{
  "data": {
    "status": "Accepted"
  }
}
```


# Remote Start / Stop

Send a command to a charger to start a charging session. These endpoints wrap the OCPP `RemoteStartTransaction` / `RemoteStopTransaction` messages (OCPP 1.6) and `RequestStartTransaction` / `RequestStopTransaction` messages (OCPP 2.0.1).

## POST /api/ocpp/remote-start

Sends a remote start command to the charger for the given port. If the request is accepted, the charger will unlock the connector and begin a transaction as if a user had initiated it locally.

### Request body

```ts
{
  portId: number;        // Flipturn charging port ID
  idTag?: string;        // Optional identifier (RFID UID, token, etc) to associate with the transaction. Max 20 characters.
  idTokenType?: string;  // Optional. OCPP 2.0.1 only. See below for valid values. Defaults to 'Central'.
}
```

If `idTag` is omitted, the default remote-start identifier is used.

**`idTokenType` values (OCPP 2.0.1 only):**

| Value             | Description                                    |
| ----------------- | ---------------------------------------------- |
| `Central`         | Server-side identifier (default)               |
| `eMAID`           | E-Mobility Account Identifier                  |
| `ISO14443`        | RFID tag (ISO 14443)                           |
| `ISO15693`        | RFID tag (ISO 15693)                           |
| `KeyCode`         | Key code / PIN                                 |
| `Local`           | Locally known identifier                       |
| `MacAddress`      | MAC address                                    |
| `NoAuthorization` | Charger should start without authorizing an id |

This field is ignored for OCPP 1.6 chargers.

### Response

```ts
{
  data: {
    status: 'Accepted' | 'Rejected';
  }
}
```

| Status     | Meaning                                                                     |
| ---------- | --------------------------------------------------------------------------- |
| `Accepted` | The charger accepted the remote start request                               |
| `Rejected` | The charger rejected the request (for example the connector is unavailable) |

### Example

**Request:**

```sh
curl -X POST "https://api.getflipturn.com/api/ocpp/remote-start" \
  -H "Authorization: Bearer {api_key}" \
  -H "Content-Type: application/json" \
  -d '{
    "portId": 34,
    "idTag": "RFID001"
  }'
```

**Response:**

```json
{
  "data": {
    "status": "Accepted"
  }
}
```

## POST /api/ocpp/remote-stop

Sends a remote stop command to the charger for an active transaction.

### Request body

```ts
{
  portId: number;         // Flipturn charging port ID
  transactionId: string;  // The OCPP transaction ID of the session to stop
}
```

For OCPP 1.6 chargers, `transactionId` must be a numeric string (e.g. `"8675309"`) — the underlying OCPP 1.6 `RemoteStopTransaction` message requires an integer. For OCPP 2.0.1 chargers it may be any string (typically a UUID).

### Response

```ts
{
  data: {
    status: 'Accepted' | 'Rejected';
  }
}
```

| Status     | Meaning                                                                     |
| ---------- | --------------------------------------------------------------------------- |
| `Accepted` | The charger accepted the remote stop request                                |
| `Rejected` | The charger rejected the request (for example the transaction is not known) |

### Example

**Request:**

```sh
curl -X POST "https://api.getflipturn.com/api/ocpp/remote-stop" \
  -H "Authorization: Bearer {api_key}" \
  -H "Content-Type: application/json" \
  -d '{
    "portId": 34,
    "transactionId": "8675309"
  }'
```

**Response:**

```json
{
  "data": {
    "status": "Accepted"
  }
}
```


# Site Power Limits

Site power limits control the total power output from all chargers on a site.

* **Capacity limit**: A hard cap. Flipturn will not allow the site to exceed this limit. Use for physical constraints (e.g. meter or transformer limits). Cannot be exceeded even by manual overrides.
* **Cost limit**: A soft cap. Use to avoid time of use rates or demand charges. Can be exceeded by a manual charging session override, setting an override schedule on a charger, or if the total minimum power for all vehicles plugged in exceeds the limit.

A site can have both a cost and a capacity limit. When both are set, the cost limit is applied first, and the capacity limit acts as a ceiling if more power is required by overrides than the cost limit allows.

**Note:** If either limit is set to 0, it will still allow vehicles to start charging at a minimum power, usually 8 A for L2 chargers and 5 kW for DCFCs.

## POST /api/site/{site-id}/limits

Creates a new site power limit. Replaces the current limit of that type. Creating schedules that vary based on time of day or day of week is supported in app, and may be supported later via the API; please reach out to <support@getflipturn.com> if you have a use case for this API functionality.

### Path parameters

* `site-id`: Flipturn site ID. Can be determined using the `sites` endpoint.

### Request body

```ts
{
  sitePowerLimitSchedule: {
    type: 'cost' | 'capacity'; // See definitions above
    limit: number; // positive integer
    chargingRateUnit: 'W' | 'A'; // 'W' (watts) or 'A' (amps).
  }
}
```

Amp-based limits (`chargingRateUnit: 'A'`) are not supported on sites that contain DCFC chargers.

**Request example**

This example will set a flat capacity limit of 100 kW on the site.

```sh
curl -X POST "https://api.getflipturn.com/api/site/42/limits" \
  -H "Authorization: Bearer {api_key}" \
  -H "Content-Type: application/json" \
  -d '{
    "sitePowerLimitSchedule": {
      "type": "capacity",
      "limit": 100000,
      "chargingRateUnit": "W"
    }
  }'
```

To set an amp-based limit instead, set `chargingRateUnit` to `"A"` and provide `limit` in amps. The example below sets a 100 A capacity limit on a Level 2-only site:

```sh
curl -X POST "https://api.getflipturn.com/api/site/42/limits" \
  -H "Authorization: Bearer {api_key}" \
  -H "Content-Type: application/json" \
  -d '{
    "sitePowerLimitSchedule": {
      "type": "capacity",
      "limit": 100,
      "chargingRateUnit": "A"
    }
  }'
```

### Response

```ts
{
  sitePowerLimitScheduleId: string;
}
```

**Example response**

```ts
{
  "sitePowerLimitScheduleId": "YTA0",
}
```

## GET /api/site/{site-id}/limits

Returns the active power limits for the site (cost and/or capacity). The response can contain up to one schedule per type. Will return an empty array if no schedules are set.

`chargingRateUnit` is `"W"` for watt-based limits (the units of the corresponding `limit` are watts) and `"A"` for amp-based limits (the units of `limit` are amps). Amp-based limits are only used on Level 2-only sites.

### Path parameters

* `site-id`: Flipturn site ID.

### Response

```ts
{
  sitePowerLimitSchedules: {
    id: string,
    createdAt: string, // DateTime from ISO 8601 as string
    source: string, // How the limit was created - "manual", "api", etc
    type: "cost" | "capacity",
    schedules: {
      daysOfWeek: number[],
      chargingRateUnit: "W" | "A",
      chargingSchedulePeriods: {
        limit: number; // watts if chargingRateUnit is "W", amps if "A"
        startPeriod: number;
      }[];
    }[]
  }[]
}
```

### Example Request and Response

**Request:**

```sh
curl "https://api.getflipturn.com/api/site/42/limits" -H "Authorization: Bearer {api_key}"
```

**Response:**

```ts
{
  "sitePowerLimitSchedules": [
    {
      "id": "MTAx",
      "createdAt": "2024-01-15T10:00:00.000Z",
      "source": "api",
      "type": "cost",
      "schedules": [
        {
          "daysOfWeek": [1, 2, 3, 4, 5],
          "chargingRateUnit": "W",
          "chargingSchedulePeriods": [
            { "startPeriod": 0, "limit": 50000 },
            { "startPeriod": 28800, "limit": 80000 }
          ]
        },
        {
          "daysOfWeek": [6, 7],
          "chargingRateUnit": "W",
          "chargingSchedulePeriods": [{ "startPeriod": 0, "limit": 80000 }]
        }
      ]
    },
    {
      "id": "MTAy",
      "createdAt": "2024-01-10T14:00:00.000Z",
      "source": "manual",
      "type": "capacity",
      "schedules": [
        {
          "daysOfWeek": [1, 2, 3, 4, 5, 6, 7],
          "chargingRateUnit": "W",
          "chargingSchedulePeriods": [{ "startPeriod": 0, "limit": 100000 }]
        }
      ]
    }
  ]
}
```

**Example response with an amp-based capacity limit (Level 2-only site):**

```ts
{
  "sitePowerLimitSchedules": [
    {
      "id": "MTAz",
      "createdAt": "2024-01-15T10:00:00.000Z",
      "source": "api",
      "type": "capacity",
      "schedules": [
        {
          "daysOfWeek": [1, 2, 3, 4, 5, 6, 7],
          "chargingRateUnit": "A",
          "chargingSchedulePeriods": [{ "startPeriod": 0, "limit": 100 }]
        }
      ]
    }
  ]
}
```

## DELETE /api/site/{site-id}/limits/{schedule-id}

Clears the site power limit for the given schedule.

### Path parameters

* `site-id`: Site ID
* `schedule-id`: Schedule ID

### Response

* **204**: No response body, if delete is successful.

### Errors

* **404**: Site or schedule not found. Use GET to see the current schedules.

### Example

**Request:**

```sh
curl -X DELETE "https://api.getflipturn.com/api/site/42/limits/MTAy" \
  -H "Authorization: Bearer {api_key}" \
  -H "Content-Type: application/json" \
```

**Response:** 204 No Content (empty body).


# Departure Times

Departure times represent scheduled departure times for vehicles. This API allows you to sync departure schedules from your Transportation Management System (TMS) into Flipturn, enabling features like:

1. **Late charging alerts** — notify when a vehicle may not be fully charged by its scheduled departure
2. **Smart charging optimization** — prioritize charging based on departure schedules
3. **Dashboard visibility** — show scheduled departures alongside charging status

## Sync workflow

The API is designed for a simple "sync" workflow where you POST all upcoming departures for a vehicle at once. This approach:

* **Atomically replaces** all future departures for the vehicle — if a trip was rescheduled, the outdated record is removed automatically
* **Leaves past departures unchanged** (for historical records)

A typical integration calls this endpoint periodically (e.g., every 5 minutes or hourly) to keep departure schedules up to date.

## POST /api/departure-times/vehicle

Sync all departure times for a specific vehicle. This endpoint:

1. Deletes all future departures for the specified vehicle
2. Filters out any past departures from the request (marks them as `skipped`)
3. Inserts the remaining future departures
4. Returns all departures with per-item `outcome` (`created` or `skipped`)

### Vehicle identification

You must provide **either** `vehicleId` or `vehicleVin` (not both).

* **By `vehicleVin`** *(recommended)*: If a vehicle with this VIN exists in Flipturn, the departures will be associated with it. If no matching vehicle exists, the departures are stored with the VIN for future matching — when the vehicle is later created in Flipturn with that VIN, the next sync call will automatically link the departures to the vehicle.
* **By `vehicleId`**: Use this if you know the Flipturn vehicle ID. Returns 404 if the vehicle doesn't exist.

### Request Body

```ts
{
  vehicleVin?: string;  // Either VIN or vehicle ID must be provided
  vehicleId?: number;
  departureTimes: {
    departureTime: string;   // (required) ISO 8601 datetime with optional timezone offset
    shiftName?: string;      // Name of the shift — primary display name
    routeName?: string;      // Name of the first route — secondary display name
    targetSoc?: number;      // Target state-of-charge (0–100), defaults to 90
  }[];
}
```

### Response

Each departure in the response includes an `outcome` field:

* `created` — the departure was successfully inserted
* `skipped` — the departure time is in the past and was not inserted

```ts
{
  departureTimes: {
    departureTime: string;   // ISO 8601 datetime (UTC)
    outcome: string;         // "created" | "skipped"
    id: number | null;       // Populated when created, null when skipped
    vehicleId: number | null;
    vehicleVin: string | null;
    shiftName: string | null;
    routeName: string | null;
    targetSoc: number | null;
  }[];
}
```

### Example: sync by vehicle ID

Request:

```sh
curl -X POST "https://api.getflipturn.com/api/departure-times/vehicle" \
-H "Authorization: Bearer {api_key}" \
-H "Content-Type: application/json" \
-d '{
  "vehicleId": 123,
  "departureTimes": [
    {
      "departureTime": "2026-02-05T06:00:00-05:00",
      "shiftName": "Morning Route",
      "routeName": "Route 42",
      "targetSoc": 90
    },
    {
      "departureTime": "2026-02-05T14:00:00-05:00",
      "shiftName": "Afternoon Route",
      "routeName": "Route 42",
      "targetSoc": 80
    }
  ]
}'
```

Response:

```js
{
  "departureTimes": [
    {
      "id": 1001,
      "vehicleId": 123,
      "vehicleVin": null,
      "departureTime": "2026-02-05T11:00:00.000Z",
      "shiftName": "Morning Route",
      "routeName": "Route 42",
      "targetSoc": 90
    },
    {
      "id": 1002,
      "vehicleId": 123,
      "vehicleVin": null,
      "departureTime": "2026-02-05T19:00:00.000Z",
      "shiftName": "Afternoon Route",
      "routeName": "Route 42",
      "targetSoc": 80
    }
  ]
}
```

### Example: sync by VIN (vehicle exists)

Request:

```sh
curl -X POST "https://api.getflipturn.com/api/departure-times/vehicle" \
-H "Authorization: Bearer {api_key}" \
-H "Content-Type: application/json" \
-d '{
  "vehicleVin": "1HGBH41JXMN109186",
  "departureTimes": [
    {
      "departureTime": "2026-02-05T08:00:00-05:00",
      "shiftName": "School Run AM"
    }
  ]
}'
```

Response (vehicle matched by VIN — `vehicleId` populated, `vehicleVin` null):

```js
{
  "departureTimes": [
    {
      "id": 1003,
      "vehicleId": 456,
      "vehicleVin": null,
      "departureTime": "2026-02-05T13:00:00.000Z",
      "shiftName": "School Run AM",
      "routeName": null,
      "targetSoc": null
    }
  ]
}
```

### Example: sync by VIN (vehicle does not exist yet)

If the VIN doesn't match any existing vehicle, the departure is stored with the VIN for future matching. When the vehicle is later created in Flipturn with that VIN, the next sync call will automatically link the departures to the vehicle.

Request:

```sh
curl -X POST "https://api.getflipturn.com/api/departure-times/vehicle" \
-H "Authorization: Bearer {api_key}" \
-H "Content-Type: application/json" \
-d '{
  "vehicleVin": "NEW_VIN_12345",
  "departureTimes": [
    {
      "departureTime": "2026-02-05T07:00:00-05:00",
      "shiftName": "Early Shift"
    }
  ]
}'
```

Response (`vehicleId` null, `vehicleVin` set):

```js
{
  "departureTimes": [
    {
      "id": 1004,
      "vehicleId": null,
      "vehicleVin": "NEW_VIN_12345",
      "departureTime": "2026-02-05T12:00:00.000Z",
      "shiftName": "Early Shift",
      "routeName": null,
      "targetSoc": null
    }
  ]
}
```

### Example: clearing all future departures

To remove all future departures for a vehicle, send an empty array:

```sh
curl -X POST "https://api.getflipturn.com/api/departure-times/vehicle" \
-H "Authorization: Bearer {api_key}" \
-H "Content-Type: application/json" \
-d '{ "vehicleId": 123, "departureTimes": [] }'
```

Response:

```js
{ "departureTimes": [] }
```

### Validation errors

| Condition                                     | Status |
| --------------------------------------------- | ------ |
| Neither `vehicleId` nor `vehicleVin` provided | 400    |
| Both `vehicleId` and `vehicleVin` provided    | 400    |
| `vehicleId` does not exist in the org         | 404    |
| `targetSoc` outside 0–100                     | 400    |
| Non-org-scoped API key                        | 400    |

***

## POST /api/departure-times/batch

Sync departure times for **multiple vehicles** in a single request. Each vehicle is processed independently — if one vehicle identifier is invalid, the others still succeed.

The request body is an array of vehicle sync items. Each item follows the same rules as the single-vehicle endpoint above.

### Request Body

```ts
{
  vehicles: Array<{
    vehicleVin?: string;   // Either VIN or vehicle ID must be provided per item
    vehicleId?: number;
    departureTimes: {
      departureTime: string;   // (required) ISO 8601 datetime with optional timezone offset
      shiftName?: string;
      routeName?: string;
      targetSoc?: number;      // 0–100, defaults to 90
    }[];
  }>;
}
```

### Response

Each item in the `results` array corresponds to one input vehicle (in order). On success the departure times are included with per-item `outcome`; on error an `error` message is included instead.

```ts
{
  results: Array<{
    vehicleId: number | null;
    vehicleVin: string | null;
    outcome: string;              // "success" | "error"
    departureTimes?: {           // Present when outcome is "success"
      departureTime: string;
      outcome: string;           // "created" | "skipped"
      id: number | null;
      vehicleId: number | null;
      vehicleVin: string | null;
      shiftName: string | null;
      routeName: string | null;
      targetSoc: number | null;
    }[];
    error?: string;              // Present when outcome is "error"
  }>;
}
```

### Example request and response

```sh
curl -X POST "https://api.getflipturn.com/api/departure-times/batch" \
-H "Authorization: Bearer {api_key}" \
-H "Content-Type: application/json" \
-d '{
  "vehicles": [
    {
      "vehicleId": 123,
      "departureTimes": [
        { "departureTime": "2026-02-05T06:00:00-05:00", "shiftName": "AM Run", "targetSoc": 90 }
      ]
    },
    {
      "vehicleId": 999999,
      "departureTimes": [
        { "departureTime": "2026-02-05T06:00:00-05:00" }
      ]
    },
    {
      "vehicleVin": "1HGBH41JXMN109186",
      "departureTimes": [
        { "departureTime": "2026-02-05T14:00:00-05:00", "shiftName": "PM Run" }
      ]
    }
  ]
}'
```

Response (second vehicle failed, others succeeded):

```js
{
  "results": [
    {
      "vehicleId": 123,
      "vehicleVin": null,
      "outcome": "success",
      "departureTimes": [
        {
          "id": 1001,
          "vehicleId": 123,
          "vehicleVin": null,
          "departureTime": "2026-02-05T11:00:00.000Z",
          "shiftName": "AM Run",
          "routeName": null,
          "targetSoc": 90
        }
      ]
    },
    {
      "vehicleId": 999999,
      "vehicleVin": null,
      "outcome": "error",
      "error": "Vehicle with id 999999 not found"
    },
    {
      "vehicleId": 456,
      "vehicleVin": null,
      "outcome": "success",
      "departureTimes": [
        {
          "id": 1002,
          "vehicleId": 456,
          "vehicleVin": null,
          "departureTime": "2026-02-05T19:00:00.000Z",
          "shiftName": "PM Run",
          "routeName": null,
          "targetSoc": 90
        }
      ]
    }
  ]
}
```


# Maintenance Windows

## GET /api/maintenance-windows

Retrieve a paginated list of maintenance windows across your chargers. For parent organization API keys, this returns maintenance windows for all child organizations.

### Parameters

Parameters should be passed as query parameters on the URL.

* `afterTimestamp` - ISO 8601 date string. Returns maintenance windows that overlap with the time after this point (i.e. windows whose end time is after this timestamp)
* `beforeTimestamp` - ISO 8601 date string. Returns maintenance windows that overlap with the time before this point (i.e. windows whose start time is before this timestamp). When used together with `afterTimestamp`, returns windows overlapping the `[afterTimestamp, beforeTimestamp]` range.
* `chargerIds` - Filter to maintenance windows for specific charger IDs. To filter by multiple chargers, repeat the parameter: `&chargerIds=1&chargerIds=2`. When combined with `siteIds`, only chargers matching both filters are returned.
* `siteIds` - Filter to maintenance windows for chargers at specific site IDs. To filter by multiple sites, repeat the parameter: `&siteIds=1&siteIds=2`. When combined with `chargerIds`, only chargers matching both filters are returned.
* `organizationIds` - Filter to maintenance windows for specific organization IDs (only applicable for parent organization API keys). To filter by multiple organizations, repeat the parameter: `&organizationIds=1&organizationIds=2`. Requested IDs are intersected with the organizations accessible by the API key.
* `nextPageCursor` - When the filters match more than one page of data, pass this parameter to fetch the next page

### Response

The JSON response will contain a `data` field with a list of maintenance windows matching the filters (up to 50 per page), and a `pagination` field containing pagination details.

```ts
{
  data: {
    id: number;
    startTimestamp: string; // ISO 8601 format
    endTimestamp: string; // ISO 8601 format
    comment: string | null;
    userEmail: string; // Email of the user who created the window
    createdAt: string; // ISO 8601 format
    updatedAt: string; // ISO 8601 format
    charger: {
      id: number;
      name: string;
      manufacturer: string | null;
      model: string | null;
      networkServiceProvider: string;
      chargerType: string;
      serialNumber: string | null;
      numberOfPorts: number;
      latitude: number | null;
      longitude: number | null;
      externalId: string | null;
      ocppId: string | null;
    };
    site: {
      id: number;
      name: string;
      locationId: string | null;
    };
    organization: {
      id: number;
      name: string;
    };
  }[];
  pagination: {
    hasNextPage: boolean;
    nextPageCursor: string | null;
  };
}
```

### Example request and response

Request all maintenance windows:

```sh
curl "https://api.getflipturn.com/api/maintenance-windows" -H "Authorization: Bearer {api_key}"
```

Request maintenance windows overlapping a date range:

```sh
curl "https://api.getflipturn.com/api/maintenance-windows?afterTimestamp=2025-01-01T00:00:00Z&beforeTimestamp=2025-02-01T00:00:00Z" -H "Authorization: Bearer {api_key}"
```

Request maintenance windows for specific chargers:

```sh
curl "https://api.getflipturn.com/api/maintenance-windows?chargerIds=123&chargerIds=456" -H "Authorization: Bearer {api_key}"
```

Request maintenance windows for a specific child organization (parent org API key):

```sh
curl "https://api.getflipturn.com/api/maintenance-windows?organizationIds=5" -H "Authorization: Bearer {api_key}"
```

Response:

```json
{
  "data": [
    {
      "id": 1,
      "startTimestamp": "2025-01-15T08:00:00.000Z",
      "endTimestamp": "2025-01-15T12:00:00.000Z",
      "comment": "Dispenser Rotation",
      "userEmail": "tech@example.com",
      "createdAt": "2025-01-14T20:00:00.000Z",
      "updatedAt": "2025-01-14T20:00:00.000Z",
      "charger": {
        "id": 123,
        "name": "DCFC-001",
        "manufacturer": "ABB",
        "model": "Terra 184",
        "networkServiceProvider": "Flipturn",
        "chargerType": "DCFC",
        "serialNumber": "1234-5678",
        "numberOfPorts": 2,
        "latitude": 30.2672,
        "longitude": -97.7431,
        "externalId": "STATION-001",
        "ocppId": "CHARGER-001"
      },
      "site": {
        "id": 1,
        "name": "Main Depot",
        "locationId": null
      },
      "organization": {
        "id": 1,
        "name": "Example Transit Authority"
      }
    }
  ],
  "pagination": {
    "hasNextPage": false,
    "nextPageCursor": null
  }
}
```


# Pagination and Error Handling

## Pagination

If all the results cannot be returned in a single request on a list endpoint, you'll have to paginate and make multiple requests. The result contains a `pagination` field:

```json
{
  "data": [{ ... }]
  "pagination": {
    "hasNextPage": true,
    "nextPageCursor": "MTA0"
  };
}
```

If `hasNextPage` is true, you can get more data by passing the `nextPageCursor` into another request. Keep all of the other parameters the same as in the previous request.

```sh
curl "https://api.getflipturn.com/api/charging-sessions?startTimeAfter=2023-03-24T01:18:05.000Z&nextPageCursor=MTA0" -H "Authorization: Bearer {api_key}"
```

Once you see `"hasNextPage": false`, then there is no more data to retrieve.

## Rate Limits

Each API key is limited to making 200 requests per minute. When fetching charging sessions with the includeIntervals query parameter, the API key is limited to 1 concurrent request. Certain endpoints enforce stricter rate limits, such as charger health. If you need a higher rate limit, please get in touch and we can discuss the use case.

## Errors and Response Codes

When the API is not able to return a successful response, it will return an HTTP response code of 400 or above, along with an error message. Response codes in the 400 category indicate an issue with the request, and 500 indicates an internal issue on Flipturn's side.

For example, this request with an incorrect API key:

```sh
curl "https://api.getflipturn.com/api/charging-sessions" -H "Authorization: Bearer invalid_key"
```

Would result in a response like the following:

```
Status code: 401

Response:
{
  "error": "Invalid API key"
}
```

Here are some errors you can get:

* `400` - invalid parameters passed to API endpoint
* `401` - invalid API key or Authorization header
* `404` - endpoint doesn't exist
* `429` - exceeded rate limit


