> For the complete documentation index, see [llms.txt](https://docs.kiloiot.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.kiloiot.io/kilo-docs-fr/kilo-center/kilo-mioty-service-center/integrations/api-reference/python-examples.md).

# Exemples Python

Exemples Python exécutables pour l’API gRPC de KiloCenter — installez grpcio, générez des stubs et appelez les méthodes de liaison montante.

Cette page fournit des exemples Python exécutables pour l’API gRPC KiloCenter. Pour la référence complète de l’API, voir la Référence de l’API.

Pour la documentation générale sur gRPC en Python, voir [grpc.io/docs/languages/python](https://grpc.io/docs/languages/python/).

### Prérequis

> Toutes les commandes de ce guide supposent que votre répertoire de travail est `kilocenter-modules/`.

Installez les packages Python gRPC :

```bash
pip install grpcio grpcio-tools
```

Générez des stubs Python à partir des définitions proto :

```bash
python -m grpc_tools.protoc \
  -I KC-Core/api/proto \
  --python_out=./gen \
  --grpc_python_out=./gen \
  KC-Core/api/proto/kilocenter.proto \
  KC-Core/api/proto/core.proto \
  KC-Core/api/proto/identity.proto
```

Cela produit `kilocenter_pb2.py`, `core_pb2.py`, `identity_pb2.py`, et leurs `_grpc` correspondants dans le `gen/` répertoire.

### Obtenir l’état du système

Récupère l’état actuel du système, y compris la version, la durée de fonctionnement et l’état de santé des services.

```python
import sys
sys.path.insert(0, "gen")

import grpc
from google.protobuf.empty_pb2 import Empty

import kilocenter_pb2_grpc

# Point de terminaison gRPC KiloCenter KC-Gateway
server = "localhost:9090"

channel = grpc.insecure_channel(server)
client = kilocenter_pb2_grpc.KiloCenterServiceStub(channel)

resp = client.GetSystemStatus(Empty())

print(f"Version :             {resp.version}")
print(f"État :              {resp.status}")
print(f"Disponibilité :              {resp.uptime}")
print(f"Points de terminaison actifs :    {resp.active_endpoints}")
print(f"Stations de base actives : {resp.active_basestations}")
print(f"Messages traités :  {resp.messages_processed}")

for svc in resp.services:
    print(f"  Service : {svc.name}  healthy={svc.healthy}  latency={svc.latency_ms}ms")
```

### Lister les points de terminaison

Répertorie les points de terminaison enregistrés avec prise en charge de la pagination. Profil à fort volume : taille de page par défaut 100, maximum 1000.

```python
import sys
sys.path.insert(0, "gen")

import grpc

import kilocenter_pb2
import kilocenter_pb2_grpc

server = "localhost:9090"

channel = grpc.insecure_channel(server)
client = kilocenter_pb2_grpc.KiloCenterServiceStub(channel)

page_token = ""
page_size = 100

while True:
    resp = client.ListEndPoints(kilocenter_pb2.ListEndPointsRequest(
        page_size=page_size,
        page_token=page_token,
    ))

    print(f"Nombre total de points de terminaison : {resp.total_count}")

    for ep in resp.endpoints:
        print(f"  EUI : {ep.epEui}  Nom : {ep.name}  État : {ep.status}  Classe : {ep.ep_class}")

    if not resp.next_page_token:
        break
    page_token = resp.next_page_token
```

### Authentification

#### Édition communautaire

L’Édition communautaire fonctionne en mode mono-locataire avec l’authentification et l’application des organisations désactivées (`auth.enabled: false`, `org_enforcement_enabled: false`). Les exemples ci-dessus fonctionnent sans aucun en-tête.

#### Entreprise : principal utilisateur JWT

Nécessite trois en-têtes : `authorization`, `x-organization-id`, et `x-user-id`. La `x-user-id` la valeur doit correspondre à l’utilisateur authentifié dans le JWT. L’absence de `x-user-id` renvoie `ErrTokenUserIDHeaderRequired`; une discordance renvoie `ErrTokenIdentityMismatch`.

```python
token = "votre-jeton-JWT"
org_id = "votre-uuid-d'organisation"
user_id = "votre-uuid-utilisateur"

metadata = [
    ("authorization", "Bearer " + token),
    ("x-organization-id", org_id),
    ("x-user-id", user_id),
]

resp = client.ListEndPoints(
    kilocenter_pb2.ListEndPointsRequest(page_size=100),
    metadata=metadata,
)
```

#### Entreprise : clé API de compte de service

Nécessite deux en-têtes : `authorization` et `x-organization-id`. Ne **pas** envoyez `x-user-id` — son inclusion renvoie `ErrTokenIdentityMismatch` pour empêcher l’injection d’utilisateur.

```python
api_key = "votre-clé-API"
org_id = "votre-uuid-d'organisation"

metadata = [
    ("authorization", "Bearer " + api_key),
    ("x-organization-id", org_id),
]

resp = client.ListEndPoints(
    kilocenter_pb2.ListEndPointsRequest(page_size=100),
    metadata=metadata,
)
```


---

# 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
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.kiloiot.io/kilo-docs-fr/kilo-center/kilo-mioty-service-center/integrations/api-reference/python-examples.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
