import Alert from '@/components/docs/Alert.astro';
import Cards from '@/components/docs/Cards.astro';
import Card from '@/components/docs/Card.astro';

This section provides a description of the platform's Web API, implemented as a REST-API data package for exchange in `json` format.

## General Terms

- **Data Transfer Format**
  The Web API is implemented as a REST-API data package for exchange in json format.
- **Authentication Procedure**
  Authentication is based on a dynamically updated token, which guarantees the security of the data received and prevents token leakage.
- **Format of Variables Containing Date and Time**
  The Web API returns data of the date and time type in UNIX time or POSIX time encoding in the format `UTC: 1613376963`. When converting Unix time to a understandable date, you must specify the time zone.
- **Pagination**
  The Web API implements pagination functionality for page-by-page loading of data. Passed by parameter: `page="page number" (page=1)`. The number of records returned in the query can be specified by the per_page parameter, but no more than 1000 records.

## Authentication

Authentication is based on a dynamically updated token. In practice, it looks like this:

- Primary authentication is performed using an email and password existing in the system and a dynamic token and related attributes are received in response.
- Forming a target request to receive data with the token received in the previous step added to the HTTP request headers.
- Sending a request to the server. If the request is formed correctly, the server returns data in the response body and a new token in the response headers, while the old token becomes invalid. With a new token, we can repeat the previous step and so on.
- Upon completion of the work, the last token can be made invalid before its expiration date (SignOut).

<Alert type="info">
  To summarize, it turns out that each subsequent request to the WEB-API must contain 4 headers from
  the previous response.
</Alert>

Initial authentication uses the email and password of an existing user. To do this, you need to send a POST request to the address:

```bash
https://uztgs.uz/api/v1/auth/sign_in
```

An example request in Curl format:

```bash
curl -i --header "Content-Type: application/json" \
     --request POST \
     --data '{"email":"api@local.net","password":"Str0ngPas$"}'\
     https://uztgs.uz/api/v1/auth/sign_in
```

In response we will receive the following message:

```bash
HTTP/1.1 200 OK
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block X-Content-Type-Options: nosniff X-Download-Options: noopen X-Permitted-Cross-Domain-Policies: none Referrer-Policy: strict-origin-when-cross-origin Content-Type: application/json; charset=utf-8 access-token: tgervk9_9xicJYpmSsnnNA
token-type: Bearer
client: D-Uv3ER53873olhnNLjL9w
expiry: 1615227012
uid: api@local.net
ETag: W/"5b9bcc76f7223b72b79d9f2d31ff0fd5"
Cache-Control: max-age=0, private, must-revalidate
X-Request-Id: c18e06b4-e5bd-40b5-875d-7ac958e2fbb5
X-Runtime: 0.391069
Transfer-Encoding: chunked
{"data":{"id":6,"email":"api@local.
net","provider":"email","uid":"api@local.net","name":"API user"}}
```

In this answer we are interested in the following headings:

| Заголовок      | Описание                                                                                                                                                   |
| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `access_token` | The value of this header is used as a password for each request. The value changes with each request.                                                      |
| `client`       | This header is unique to the current connection. Allows multiple active sessions at the same time.                                                         |
| `expiry`       | The time when this token will expire. Default is 2 weeks from the moment it is received. Or SignOut for early expiration. Not needed for the next request. |
| `uid`          | A unique value identifying the user. In our case, email.                                                                                                   |
| `token-type`   | The type of token used.                                                                                                                                    |

An example request using the token from the previous response:

```bash
curl -i --header "access-token: tgervk9_9xicJYpmSsnnNA" \
 --header "token-type: Bearer" \
 --header "client: D-Uv3ER53873olhnNLjL9w" \
 --header "uid: api@local.net" \
 --request GET \
 --header "Content-Type: application/json" \
 --data '{"page":"2"}' \
 https://uztgs.uz/api/v1/stations
```

In response we will receive the following message:

```bash
HTTP/1.1 200 OK
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
X-Download-Options: noopen
X-Permitted-Cross-Domain-Policies: none
Referrer-Policy: strict-origin-when-cross-origin
Content-Type: application/json; charset=utf-8
access-token: Bmh2GVrxr6aW0Hngor4gPw
token-type: Bearer
client: D-Uv3ER53873olhnNLjL9w
expiry: 1615311367
uid: api@local.net
ETag: W/"ba0df406b647bd92f0bf3a18916714c1"
Cache-Control: max-age=0, private, must-revalidate
X-Request-Id: 35a26441-ae78-48fa-8b2e-e92d2605133b
X-Runtime: 0.167748
Transfer-Encoding: chunked
{"data": [
{"id":1,"name":"865293041101853","equipment_brand_name":"Corrector BK","phone":"","equipment_id":1},...
 ],
"total_pages":7,
"current_page":2
}
```

To complete the work, you can use the SignOut procedure, or save the necessary headers from the last request and, if the token lifetime has not expired, use them next time.

<Alert type="warning">
  Please remember that without terminating the session, the last token will be valid for two weeks.
</Alert>

Ending a session:

```bash
curl -i --header "access-token: Bmh2GVrxr6aW0Hngor4gPw" \
 --header "token-type: Bearer" \
 --header "client: D-Uv3ER53873olhnNLjL9w" \
 --header "uid: api@local.net" \
 --request DELETE \
 https://uztgs.uz/api/v1/auth/sign_out
HTTP/1.1 200 OK
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
X-Download-Options: noopen
X-Permitted-Cross-Domain-Policies: none
Referrer-Policy: strict-origin-when-cross-origin
Content-Type: application/json; charset=utf-8
ETag: W/"c955e57777ec0d73639dca6748560d00"
Cache-Control: max-age=0, private, must-revalidate
X-Request-Id: b4b69ac3-5cba-4e6e-b6a0-f6577298c166
X-Runtime: 0.141467
Transfer-Encoding: chunked
{"success":true}
```

## Next Steps

Now that you can authenticate, explore the core resources of the API:

<Cards cols={2}>
  <Card
    icon="network"
    title="Resource providers & consumers"
    description="List the provider hierarchy and the consumers they serve."
    link="/en/api/v1/resource-providers-and-consumers"
  />
  <Card
    icon="gauge"
    title="Metering units"
    description="List metered stations and read their physical characteristics."
    link="/en/api/v1/metering-units"
  />
  <Card
    icon="archive"
    title="Readings archives"
    description="Retrieve channel readings by archive type and time interval."
    link="/en/api/v1/readings-archives"
  />
  <Card
    icon="bell"
    title="Events & messages"
    description="Read device event archives and the message-code reference."
    link="/en/api/v1/events-and-messages"
  />
</Cards>