API Usage and Integration Patterns for KCloud-Platform-IoT: A Complete Developer Guide
KCloud-Platform-IoT exposes versioned REST endpoints through layered Spring Boot adapters that use DTO-driven commands and queries, with cross-cutting concerns handled via declarative annotations for idempotency, audit logging, and security.
KCloud-Platform-IoT is an open-source IoT management platform built on Spring Boot 4 and Spring Cloud 2025, following Alibaba COLA architecture conventions. Understanding the API usage and integration patterns for KCloud-Platform-IoT enables developers to interact with device management, product catalogs, and thing models through a consistent, secure interface. This guide examines the actual source implementation to demonstrate how controllers, service contracts, and data transfer objects collaborate to handle HTTP requests in this microservices ecosystem.
Layered Architecture Overview
KCloud-Platform-IoT implements a layered micro-service architecture that cleanly separates HTTP concerns from business logic. The architecture consists of four primary layers:
- Adapters (REST Controllers) – Expose HTTP/JSON endpoints under the
/v1/prefix. Controllers reside in thelaokou-iot-adaptermodule. - Service Interfaces (
*ServiceI) – Define business contracts in thelaokou-iot-clientmodules, implemented by*ServiceImplclasses in thelaokou-iot-appmodules. - DTOs (Cmd/Qry/CO) – Lightweight request/response objects. Commands (
*Cmd) handle writes, Queries (*Qry) handle reads, and Client Objects (*CO) represent responses. - Cross-cutting concerns – Handled declaratively via
@Idempotent,@OperateLog,@TraceLog, and Spring Security annotations applied directly on controller methods.
All public APIs are documented with OpenAPI annotations (@Operation, @Tag) and auto-generate Swagger UI via Springdoc.
Request Flow Through the System
The typical HTTP request follows a strict pipeline through the architecture:
HTTP Request → Adapter (Controller) → ServiceI (Business contract) → ServiceImpl (业务实现) → Repository/Message Queue/External System
The controller validates incoming payloads using @Validated and forwards either a Cmd or Qry object to the service interface. The service implementation executes core business logic—such as persisting device metadata or publishing MQTT events. Finally, responses are wrapped in Result<T> (or Page<T> for pagination) and serialized to a standard JSON envelope by the global exception handler.
Core API Groups and Endpoints
The platform organizes IoT functionality into domain-specific controllers, each following consistent naming conventions and base paths.
Device Management
The DevicesController handles device lifecycle operations at the base path /v1/devices.
- Service Interface:
DevicesServiceI(defined inlaokou-iot-client) - Key DTOs:
DeviceSaveCmd,DeviceModifyCmd,DevicePageQry,DeviceExportCmd,DeviceCO
Product Management
The ProductsController manages product definitions at /v1/products.
- Service Interface:
ProductsServiceI - Key DTOs:
ProductSaveCmd,ProductModifyCmd,ProductPageQry,ProductExportCmd,ProductCO
Thing Model and Product Category
- Thing Models:
ThingModelsControllerexposes/v1/thing-modelswithThingModelSaveCmd,ThingModelPageQry, andThingModelCO. - Product Categories:
ProductCategorysControllerexposes/v1/product-categoryswith correspondingProductCategoryDTOs.
Practical API Integration Examples
Creating a Device
To create a device, POST a JSON payload that maps to DeviceSaveCmd:
curl -X POST https://api.my-iot.com/v1/devices \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <jwt-token>" \
-d '{
"name": "TempSensor-001",
"productId": 12,
"devEui": "A1B2C3D4E5F6",
"description": "Warehouse temperature sensor"
}'
This request flows through DevicesServiceI.saveDevice to DevicesServiceImpl.saveDevice.
Paginated Queries
For paginated device listings, use the DevicePageQry DTO:
curl -X POST https://api.my-iot.com/v1/devices/page \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <jwt-token>" \
-d '{
"pageNum": 1,
"pageSize": 20,
"name": "TempSensor"
}'
The endpoint returns Result<Page<DeviceCO>>, where the Result wrapper provides standard status codes and the Page object contains the collection of DeviceCO objects.
Bulk Import and Export
Import operations accept multipart/form-data and map to DeviceImportCmd:
curl -X POST https://api.my-iot.com/v1/devices/import \
-H "Authorization: Bearer <jwt-token>" \
-F "files=@/path/to/devices.xlsx"
Export operations stream Excel files using EasyExcel or Apache POI:
curl -X POST https://api.my-iot.com/v1/devices/export \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <jwt-token>" \
-d '{"ids": [101, 102, 103]}' \
-o devices.xlsx
The export triggers DevicesServiceI.exportDevice, which handles the streaming response.
Security and Cross-Cutting Concerns
Method-Level Security
All endpoints are protected with Spring Security expressions. For example, device creation requires specific authorities:
@PreAuthorize("hasAuthority('write') and hasAuthority('iot:device:save')")
Users must obtain JWT tokens from the auth service that contain these authority strings.
Idempotent Writes
The @Idempotent annotation prevents duplicate submissions on POST and PUT operations. This is implemented via token-based verification or Redis distributed locks, ensuring that network retries do not create duplicate devices or products.
Observability and Audit
@OperateLog– Records operation metadata (module, action) to the audit log via the admin service.@TraceLog– Injects request-trace IDs for distributed tracing with Jaeger or Zipkin, primarily applied to pagination and detail queries.
Integration Patterns for Microservices
When calling KCloud-Platform-IoT APIs from another micro-service (such as an API gateway or edge node), follow these patterns:
- Use Spring WebClient (reactive) or RestTemplate (blocking) targeting the IoT service base URL.
- Propagate the JWT token in the
Authorizationheader obtained from the auth service. - Serialize DTOs exactly as defined in the source code—simple POJOs with Lombok getters/setters located in
laokou-iot-common.
Example WebClient integration:
WebClient client = WebClient.builder()
.baseUrl("https://api.my-iot.com")
.defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token)
.build();
Mono<Result<Page<DeviceCO>>> page = client.post()
.uri("/v1/devices/page")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(new DevicePageQry(1, 20, "TempSensor"))
.retrieve()
.bodyToMono(new ParameterizedTypeReference<Result<Page<DeviceCO>>>(){});
Key Source Files Reference
| Component | File Path | Direct Link |
|---|---|---|
| Device Controller | laokou-service/laokou-iot/laokou-iot-adapter/src/main/java/org/laokou/iot/web/DevicesController.java |
View Source |
| Device Service Interface | laokou-service/laokou-iot/laokou-iot-client/src/main/java/org/laokou/iot/device/api/DevicesServiceI.java |
View Source |
| Device Service Implementation | laokou-service/laokou-iot/laokou-iot-app/src/main/java/org/laokou/iot/device/service/DevicesServiceImpl.java |
View Source |
| Device DTOs | laokou-service/laokou-iot/laokou-iot-client/src/main/java/org/laokou/iot/device/dto/ |
View Directory |
| Product Controller | laokou-service/laokou-iot/laokou-iot-adapter/src/main/java/org/laokou/iot/web/ProductsController.java |
View Source |
| Response Wrapper | laokou-common/laokou-common-i18n/src/main/java/org/laokou/common/i18n/dto/Result.java |
View Source |
| Pagination Wrapper | laokou-common/laokou-common-i18n/src/main/java/org/laokou/common/i18n/dto/Page.java |
View Source |
Summary
- REST adapters expose a clean, versioned API surface under
/v1/with OpenAPI documentation. - Service contracts (
*ServiceI) keep business logic decoupled from HTTP transport concerns, enabling testability and reuse. - DTO-centric design using Commands (
*Cmd), Queries (*Qry), and Client Objects (*CO) ensures stable, language-agnostic payload contracts. - Cross-cutting annotations—
@Idempotent,@OperateLog,@TraceLog, and@PreAuthorize—handle infrastructure concerns automatically without polluting business code. - Import/export functionality leverages EasyExcel or Apache POI for streaming Excel processing via multipart form data endpoints.
Frequently Asked Questions
How do I authenticate requests to KCloud-Platform-IoT APIs?
KCloud-Platform-IoT uses Spring Security with JWT tokens issued by the auth service. You must include an Authorization: Bearer <token> header where the token contains authorities like iot:device:save. Controllers validate these using @PreAuthorize annotations that check for specific permission strings.
What is the difference between Cmd and Qry DTOs in KCloud-Platform-IoT?
Cmd (Command) DTOs such as DeviceSaveCmd represent write operations that modify state, while Qry (Query) DTOs like DevicePageQry represent read-only operations. This Command Query Responsibility Segregation (CQRS) pattern separates the data structures for creating resources from those for searching or filtering, allowing the API to evolve independently for reads versus writes.
How does KCloud-Platform-IoT prevent duplicate API submissions?
The platform uses the @Idempotent annotation on controller methods to prevent duplicate submissions. This implementation uses either token-based verification or Redis distributed locks to ensure that retries due to network timeouts do not result in duplicate device registrations or product modifications.
Can I integrate KCloud-Platform-IoT APIs from non-Java services?
Yes, the APIs are standard HTTP/JSON endpoints. While the DTOs are defined as Java classes in laokou-iot-common, they are simple POJOs that serialize to predictable JSON structures. Any client capable of making HTTP requests and parsing JSON—including Python, Node.js, or Go applications—can interact with the endpoints by replicating the field structures found in the source DTO files.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →