> 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-es/kilo-center/kilo-mioty-service-center/integrations/api-reference/python-examples.md).

# Ejemplos en Python

Ejemplos ejecutables en Python para la API gRPC de KiloCenter — instala grpcio, genera stubs y llama a métodos de uplink.

Esta página proporciona ejemplos ejecutables de Python para la API gRPC de KiloCenter. Para la referencia completa de la API, consulte la Referencia de la API.

Para la documentación general de gRPC en Python, consulte [grpc.io/docs/languages/python](https://grpc.io/docs/languages/python/).

### Requisitos previos

> Todos los comandos de esta guía asumen que su directorio de trabajo es `kilocenter-modules/`.

Instale los paquetes de gRPC para Python:

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

Genere stubs de Python a partir de las definiciones 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
```

Esto produce `kilocenter_pb2.py`, `core_pb2.py`, `identity_pb2.py` y sus `_grpc` equivalentes en el `gen/` directorio.

### Obtener estado del sistema

Recupera el estado actual del sistema, incluida la versión, el tiempo de actividad y el estado de los servicios.

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

import grpc
from google.protobuf.empty_pb2 import Empty

import kilocenter_pb2_grpc

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

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

resp = client.GetSystemStatus(Empty())

print(f"Versión:             {resp.version}")
print(f"Estado:              {resp.status}")
print(f"Tiempo de actividad:              {resp.uptime}")
print(f"Endpoints activos:    {resp.active_endpoints}")
print(f"Estaciones base activas: {resp.active_basestations}")
print(f"Mensajes procesados:  {resp.messages_processed}")

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

### Listar puntos finales

Lista los puntos finales registrados con compatibilidad de paginación. Perfil de alto volumen: tamaño de página predeterminado 100, máximo 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"Total de endpoints: {resp.total_count}")

    for ep in resp.endpoints:
        print(f"  EUI: {ep.epEui}  Nombre: {ep.name}  Estado: {ep.status}  Clase: {ep.ep_class}")

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

### Autenticación

#### Edición comunitaria

La Edición comunitaria se ejecuta en modo de inquilino único con la autenticación y la aplicación de la organización deshabilitadas (`auth.enabled: false`, `org_enforcement_enabled: false`). Los ejemplos anteriores funcionan sin ningún encabezado.

#### Enterprise: principal de usuario JWT

Requiere tres encabezados: `authorization`, `x-organization-id`, y `x-user-id`. El `x-user-id` el valor debe coincidir con el usuario autenticado en el JWT. Si falta `x-user-id` devuelve `ErrTokenUserIDHeaderRequired`; una discordancia devuelve `ErrTokenIdentityMismatch`.

```python
token = "your-jwt-token"
org_id = "your-organization-uuid"
user_id = "your-user-uuid"

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,
)
```

#### Enterprise: clave API de cuenta de servicio

Requiere dos encabezados: `authorization` y `x-organization-id`. Haga **no** enviar `x-user-id` — incluirlo devuelve `ErrTokenIdentityMismatch` para evitar la inyección de usuarios.

```python
api_key = "your-api-key"
org_id = "your-organization-uuid"

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-es/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.
