Lemline documentation Help

API Integration Examples

This document provides practical examples of API integrations in Lemline workflows. It demonstrates different approaches to connecting with REST APIs, GraphQL, OpenAPI, gRPC, and other API types, covering authentication, error handling, and data transformation.

Run the Examples

Complete the SQLite setup and run the commands from the setup directory. With the JAR, substitute java -jar lemline.jar for bin/lemline. Start the tutorial shop from the root of the Lemline source checkout:

docker compose -f examples/tutorial-services/compose.yaml up -d

The examples read their API keys and tokens from secrets. The shop accepts any value on these routes and lists the headers it received under Requests. Stop the setup worker with Ctrl+C, export demo values, and start it again:

export API_KEY='demo-api-key' export EMAIL_SERVICE_TOKEN='demo-token' export API_TOKEN='demo-token' bin/lemline listen --debug

Run the other commands from a second terminal in the setup directory.

REST API Integration Examples

Basic REST API Workflow

This example demonstrates a simple workflow that interacts with multiple REST endpoints.

document: dsl: '1.0.3' namespace: examples name: register-customer version: '1.0.0' input: schema: format: json document: type: object required: - email - name properties: email: type: string format: email name: type: string use: secrets: - API_KEY - EMAIL_SERVICE_TOKEN do: - validateEmail: call: http with: method: post endpoint: http://127.0.0.1:8787/email-checks body: email: ${ .email } export: as: '${ $context + { emailValidation: . } }' - createUserAccount: do: - route: switch: - validEmail: when: ${ $context.emailValidation.valid == true } then: validEmailAction - default: then: defaultAction - validEmailAction: do: - registerUser: call: http with: method: post endpoint: http://127.0.0.1:8787/customers headers: Content-Type: application/json X-API-Key: ${ $secrets.API_KEY } body: email: ${ $workflow.input.email } name: ${ $workflow.input.name } export: as: '${ $context + { userAccount: . } }' - sendWelcomeEmail: call: http with: method: post endpoint: http://127.0.0.1:8787/notifications headers: Content-Type: application/json Authorization: Bearer ${ $secrets.EMAIL_SERVICE_TOKEN } body: reference: ${ $context.userAccount.id } recipient: ${ $workflow.input.email } message: '${ "Welcome, " + $workflow.input.name }' then: exit - defaultAction: do: - notifyInvalidEmail: set: result: success: false reason: Invalid email address email: ${ $context.emailValidation.email } then: exit

Save it as basic-rest-api-workflow.yaml:

bin/lemline definition post -f basic-rest-api-workflow.yaml bin/lemline instance start examples register-customer --input '{"email":"katherine@example.com","name":"Katherine Johnson"}' bin/lemline instance start examples register-customer --input '{"email":"katherine@localhost","name":"Katherine Johnson"}'

The first email is valid for the shop: the customer is created as C-901 and a Welcome, Katherine Johnson message reaches their inbox. The workflow input schema accepts katherine@localhost, but the shop's check requires a domain with a dot: the second instance completes with {"result":{"success":false,"reason":"Invalid email address","email":"katherine@localhost"}}.

Pagination Handling

This example shows how to handle paginated API responses.

document: dsl: '1.0.3' namespace: examples name: pagination-handling version: '1.0.0' do: - initializeProductList: set: allProducts: [] nextPage: 1 hasMorePages: true export: as: '${ $context + { allProducts: [], nextPage: 1, hasMorePages: true } }' - fetchAllPages: for: in: ${ range(0; 10000) } while: ${ $context.hasMorePages } do: - fetchNextProductPage: call: http with: method: get endpoint: http://127.0.0.1:8787/products query: page: ${ $context.nextPage | tostring } size: '3' export: as: '${ $context + { pageResult: . } }' - processPage: set: allProducts: ${ $context.allProducts + $context.pageResult.items } nextPage: ${ $context.nextPage + 1 } hasMorePages: ${ $context.pageResult.hasMore } export: as: '${ $context + { allProducts: ($context.allProducts + $context.pageResult.items), nextPage: ($context.nextPage + 1), hasMorePages: $context.pageResult.hasMore } }' - processFinalResult: set: result: totalProducts: ${ $context.allProducts | length } productIds: ${ [$context.allProducts[].id] }

Save it as pagination-handling.yaml:

bin/lemline definition post -f pagination-handling.yaml bin/lemline instance start examples pagination-handling

The shop returns three products per page. The loop reads pages 1 to 3 and stops when hasMore is false: expect totalProducts 7 and the seven IDs from SKU-1 to SKU-7.

Request Throttling

This example demonstrates how to implement API request throttling to respect rate limits.

document: dsl: '1.0.3' namespace: examples name: request-throttling version: '1.0.0' input: schema: format: json document: type: object required: - items properties: items: type: array items: type: string use: secrets: - API_TOKEN do: - initializeContext: set: processedItems: [] failures: [] export: as: '${ $context + { processedItems: [], failures: [] } }' - processBatches: for: in: '${ $workflow.input.items as $items | [range(0; ($items | length); 5) as $i | $items[$i:$i + 5]] }' each: batch do: - processBatch: for: in: ${ $batch } each: item do: - processItem: try: - callRateLimitedAPI: call: http with: method: get endpoint: '${ "http://127.0.0.1:8787/products/\($item)?fail=429&failTimes=\(if $item == "SKU-2" then 1 else 0 end)&key=\($workflow.id)" }' headers: Authorization: Bearer ${ $secrets.API_TOKEN } export: as: '${ $context + { processedItems: ($context.processedItems + [.]) } }' catch: errors: with: type: https://open-workflow-specification.org/spec/1.0.0/errors/communication as: apiError retry: when: ${ $apiError.status == 429 } delay: seconds: 10 backoff: exponential: {} limit: attempt: count: 3 do: - recordFailure: set: failure: item: ${ $item } error: ${ $apiError } export: as: '${ $context + { failures: ($context.failures + [.failure]) } }' - throttleBetweenBatches: wait: seconds: 2 - summarizeResults: set: result: succeeded: ${ $context.processedItems | length } failed: ${ $context.failures | length } processedItems: ${ $context.processedItems } failures: ${ $context.failures }

Save it as request-throttling.yaml:

bin/lemline definition post -f request-throttling.yaml bin/lemline instance start examples request-throttling --input '{"items":["SKU-1","SKU-2","SKU-3","SKU-4","SKU-5","SKU-404"]}'

The items are processed in batches of five, with a 2-second pause after each batch. The shop answers HTTP 429 once for SKU-2: that call is retried after 10 seconds and succeeds. SKU-404 gets HTTP 404, which is not retried and is recorded as a failure. Expect succeeded: 5 and failed: 1. Allow about a minute: the worker picks up retries every 10 seconds.

OpenAPI Integration Examples

OpenAPI Specification Integration

This example demonstrates how to use an OpenAPI specification for API integration.

document: dsl: 1.0.3 namespace: examples name: catalog-openapi version: 1.0.0 do: - listGardenProducts: call: openapi with: document: endpoint: http://127.0.0.1:8787/openapi.json operationId: listProducts parameters: category: garden export: as: '${ $context + { gardenProducts: . } }' - retrieveFirstProduct: call: openapi with: document: endpoint: http://127.0.0.1:8787/openapi.json operationId: getProduct parameters: productId: ${ $context.gardenProducts.items[0].id } export: as: '${ $context + { firstProduct: . } }'

Save it as openapi-specification-integration.yaml:

bin/lemline definition post -f openapi-specification-integration.yaml bin/lemline instance start examples catalog-openapi

The definition targets the shop's OpenAPI document; the instance faults with Unknown task type: CallOpenAPI.

OpenAPI with Authentication

This example shows OpenAPI integration with different authentication methods.

document: dsl: 1.0.3 namespace: examples name: openapi-auth version: 1.0.0 use: secrets: - CLIENT_ID - CLIENT_SECRET - USERNAME - PASSWORD do: - callWithOAuth2: call: openapi with: document: endpoint: http://127.0.0.1:8787/openapi.json operationId: createResource authentication: oauth2: authority: http://127.0.0.1:8787/oauth2 grant: client_credentials client: id: ${ $secrets.CLIENT_ID } secret: ${ $secrets.CLIENT_SECRET } scopes: - resource.write parameters: body: name: Example Resource type: test export: as: '${ $context + { oauth2Result: . } }' - callWithBasicAuth: call: openapi with: document: endpoint: http://127.0.0.1:8787/openapi.json operationId: deleteResource authentication: basic: username: ${ $secrets.USERNAME } password: ${ $secrets.PASSWORD } parameters: resourceId: ${ $context.oauth2Result.id }

Lemline cannot run this one either: besides the OpenAPI call, it has no OAuth 2.0 support.

GraphQL Integration Examples

Basic GraphQL Query

This example demonstrates a basic GraphQL query using HTTP integration.

document: dsl: '1.0.3' namespace: examples name: customer-graphql-query version: '1.0.0' input: schema: format: json document: type: object required: - customerId properties: customerId: type: string use: secrets: - API_TOKEN do: - fetchCustomerData: call: http with: method: post endpoint: http://127.0.0.1:8787/graphql headers: Content-Type: application/json Authorization: Bearer ${ $secrets.API_TOKEN } body: query: | query GetCustomer($id: ID!) { customer(id: $id) { id name email reviews { id rating title } orders { totalCount } } } variables: id: ${ .customerId } export: as: '${ $context + { graphqlResponse: . } }' - processCustomerData: set: customerName: ${ $context.graphqlResponse.data.customer.name } totalReviews: ${ $context.graphqlResponse.data.customer.reviews | length } orderCount: ${ $context.graphqlResponse.data.customer.orders.totalCount }

Save it as basic-graphql-query.yaml:

bin/lemline definition post -f basic-graphql-query.yaml bin/lemline instance start examples customer-graphql-query --input '{"customerId":"C-100"}'

The shop's GraphQL stand-in answers the customer query: expect {"customerName":"Ada Lovelace","totalReviews":2,"orderCount":0}.

GraphQL Mutation

This example demonstrates a GraphQL mutation.

document: dsl: '1.0.3' namespace: examples name: add-review-mutation version: '1.0.0' input: schema: format: json document: type: object required: - review properties: review: type: object required: - customerId - productId - rating use: secrets: - API_TOKEN do: - addReview: call: http with: method: post endpoint: http://127.0.0.1:8787/graphql headers: Content-Type: application/json Authorization: Bearer ${ $secrets.API_TOKEN } body: query: | mutation AddReview($review: ReviewInput!) { addReview(review: $review) { id rating title } } variables: review: ${ .review } export: as: '${ $context + { graphqlResponse: . } }' - processResult: do: - route: switch: - hasErrors: when: ${ ($context.graphqlResponse.errors // []) | length > 0 } then: hasErrorsAction - default: then: defaultAction - hasErrorsAction: do: - handleErrors: set: result: success: false errors: ${ [$context.graphqlResponse.errors[].message] } then: exit - defaultAction: do: - handleSuccess: set: result: success: true review: ${ $context.graphqlResponse.data.addReview } then: exit

Save it as graphql-mutation.yaml:

bin/lemline definition post -f graphql-mutation.yaml bin/lemline instance start examples add-review-mutation --input '{"review":{"customerId":"C-200","productId":"SKU-2","rating":4,"title":"Good can"}}' bin/lemline instance start examples add-review-mutation --input '{"review":{"customerId":"C-200","productId":"SKU-404","rating":9}}'

The first instance returns {"result":{"success":true,"review":{"id":"R-3","rating":4,"title":"Good can"}}}. The second gets GraphQL errors for the unknown product and the rating: {"result":{"success":false,"errors":["Unknown product SKU-404","Rating must be from 1 to 5"]}}.

gRPC Integration Examples

Basic gRPC Service Call

This example demonstrates integrating with a gRPC service.

document: dsl: 1.0.3 namespace: examples name: grpc-integration version: 1.0.0 input: schema: format: json document: type: object required: - username properties: username: type: string do: - greetUser: call: grpc with: proto: endpoint: file:///protos/greeter.proto service: name: Greeter host: grpc-example port: 50051 method: SayHello arguments: name: ${ .username } export: as: '${ $context + { greeting: . } }' - getUserProfile: call: grpc with: proto: endpoint: file:///protos/user_service.proto service: name: UserService host: grpc-example port: 50051 method: GetUserProfile arguments: username: ${ $workflow.input.username } export: as: '${ $context + { userProfile: . } }' - combineResults: set: result: greeting: ${ $context.greeting.message } profile: userId: ${ $context.userProfile.id } displayName: ${ $context.userProfile.displayName } email: ${ $context.userProfile.email } joinDate: ${ $context.userProfile.joinDate }

Lemline registers this definition; an instance faults with Unknown task type: CallGRPC. See How to describe a gRPC call for the HTTP equivalent on the shop.

gRPC with Authentication

This example demonstrates a gRPC call authenticated with OAuth2 client credentials.

document: dsl: '1.0.3' namespace: examples name: grpc-auth-example version: '0.1.0' use: secrets: - apiToken authentications: inventoryAuth: bearer: token: ${ $secrets.apiToken } do: - getStock: call: grpc with: proto: endpoint: file:///opt/shop/inventory.proto service: name: shop.InventoryService host: localhost port: 50051 authentication: use: inventoryAuth method: GetStock arguments: sku: ${ .sku } - recordStock: set: checked: true

This one fails the same way.

AsyncAPI Integration Examples

Event-Driven API Integration

This example demonstrates AsyncAPI integration for event-driven architectures.

document: dsl: 1.0.3 namespace: examples name: event-driven-workflow version: 1.0.0 do: - listenForOrder: call: asyncapi with: document: endpoint: file:///apis/order-service.asyncapi.json operation: receiveOrder subscription: filter: ${ .type == "new-order" } consume: amount: 1 export: as: '${ $context + { order: . } }' - processOrder: call: http with: method: post endpoint: https://inventory.example/api/check-availability body: orderId: ${ $context.order.id } items: ${ $context.order.items } export: as: '${ $context + { availabilityCheck: . } }' - publishOrderStatus: call: asyncapi with: document: endpoint: file:///apis/order-service.asyncapi.json operation: publishOrderStatus message: payload: orderId: ${ $context.order.id } status: '${ if $context.availabilityCheck.allItemsAvailable then "confirmed" else "backorder" end }' availableItems: ${ $context.availabilityCheck.availableItems } unavailableItems: ${ $context.availabilityCheck.unavailableItems }

Lemline has no AsyncAPI executor: the task fails with Unknown task type: CallAsyncAPI. Use emit and listen, as in How to emit and listen for events, to exchange events on Lemline's own channel.

Message Streaming with AsyncAPI

This example shows how to process a stream of messages with AsyncAPI: each sensor reading is sent to an analysis service, and an alert is published when the analysis asks for one. A failed call is retried up to three times.

document: dsl: 1.0.3 namespace: examples name: stream-processing version: 1.0.0 do: - processTelemetryStream: call: asyncapi with: document: endpoint: file:///apis/telemetry.asyncapi.json operation: subscribeTelemetry subscription: filter: '${ .deviceType == "sensor" }' consume: while: ${ true } foreach: item: reading do: - processReading: try: - analyzeTelemetry: call: http with: method: post endpoint: https://analytics.example/api/analyze body: ${ $reading } - triggerAlert: if: ${ .alertRequired == true } call: asyncapi with: document: endpoint: file:///apis/telemetry.asyncapi.json operation: publishAlert message: payload: deviceId: ${ $reading.deviceId } alertType: ${ .alertType } severity: ${ .severity } value: ${ $reading.value } timestamp: ${ $reading.timestamp } catch: errors: with: type: https://open-workflow-specification.org/spec/1.0.0/errors/communication retry: delay: seconds: 2 limit: attempt: count: 3

This one fails the same way. Stop the shop when you are done:

docker compose -f examples/tutorial-services/compose.yaml down

API Integration Best Practices

When implementing API integrations in Lemline workflows, consider these best practices:

  1. Authentication Management: Use secrets for managing API credentials securely

  2. Request Validation: Validate input data before making API calls

  3. Response Validation: Validate API responses against expected schemas

  4. Error Handling: Implement robust error handling with appropriate retry policies

  5. Rate Limiting: Respect API rate limits by implementing throttling or backoff strategies

  6. Pagination: Handle paginated API responses properly

  7. Idempotency: Design workflows to handle API call retries safely

  8. Circuit Breaking: Implement circuit breaking for failing endpoints

  9. Monitoring: Include appropriate logging for API interactions

  10. Timeout Handling: Set appropriate timeouts for API calls (Lemline only enforces timeouts on listen tasks; HTTP calls use fixed limits of 15 s to connect and 30 s per request)

Conclusion

These examples demonstrate how to implement various API integration patterns in Lemline workflows. By leveraging the Open Workflow DSL's capabilities, you can build robust API integrations that handle authentication, error conditions, pagination, and other common challenges.

Whether you're working with REST APIs, GraphQL, OpenAPI specifications, gRPC services, or event-driven AsyncAPI definitions, Lemline provides a consistent approach to API integration that emphasizes reliability, security, and maintainability.

For more examples of error handling in API integrations, see the Error Handling Examples document.

25 November 2026