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

# Exemplos em Python

Exemplos executáveis em Python para a API gRPC do KiloCenter — instale grpcio, gere stubs e chame métodos de uplink.

Esta página fornece exemplos executáveis em Python para a API gRPC do KiloCenter. Para a referência completa da API, consulte a Referência da API.

Para documentação geral do gRPC em Python, consulte [grpc.io/docs/languages/python](https://grpc.io/docs/languages/python/).

### Pré-requisitos

> Todos os comandos deste guia assumem que o seu diretório de trabalho é `kilocenter-modules/`.

Instale os pacotes gRPC Python:

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

Gere stubs Python a partir das definições 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
```

Isto produz `kilocenter_pb2.py`, `core_pb2.py`, `identity_pb2.py`, e os seus `_grpc` correspondentes em `gen/` diretório.

### Obter estado do sistema

Obtém o estado atual do sistema, incluindo versão, tempo de atividade e estado dos serviços.

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

import grpc
from google.protobuf.empty_pb2 import Empty

import kilocenter_pb2_grpc

# endpoint gRPC do KC-Gateway do KiloCenter
server = "localhost:9090"

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

resp = client.GetSystemStatus(Empty())

print(f"Versão:             {resp.version}")
print(f"Estado:              {resp.status}")
print(f"Tempo de atividade:  {resp.uptime}")
print(f"Endpoints ativos:    {resp.active_endpoints}")
print(f"Estações base ativas: {resp.active_basestations}")
print(f"Mensagens processadas:  {resp.messages_processed}")

for svc in resp.services:
    print(f"  Serviço: {svc.name}  saudável={svc.healthy}  latência={svc.latency_ms}ms")
```

### Listar endpoints

Lista os endpoints registados com suporte para paginação. Perfil de alto volume: tamanho de página predefinido 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}  Nome: {ep.name}  Estado: {ep.status}  Classe: {ep.ep_class}")

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

### Autenticação

#### Edição Comunitária

A Edição Comunitária é executada em modo de inquilino único com autenticação e aplicação da organização desativadas (`auth.enabled: false`, `org_enforcement_enabled: false`). Os exemplos acima funcionam sem quaisquer cabeçalhos.

#### Enterprise: Principal do utilizador JWT

Requer três cabeçalhos: `authorization`, `x-organization-id`, e `x-user-id`. A `x-user-id` o valor deve corresponder ao utilizador autenticado no JWT. Em falta `x-user-id` retorna `ErrTokenUserIDHeaderRequired`; uma incompatibilidade retorna `ErrTokenIdentityMismatch`.

```python
token = "seu-token-jwt"
org_id = "seu-uuid-da-organização"
user_id = "seu-uuid-do-usuário"

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: Chave API da conta de serviço

Requer dois cabeçalhos: `authorization` e `x-organization-id`. Não **não** envie `x-user-id` — incluí-lo retorna `ErrTokenIdentityMismatch` para evitar injeção de utilizador.

```python
api_key = "sua-chave-da-API"
org_id = "seu-uuid-da-organização"

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