1 - Service invocation API reference

Detailed documentation on the service invocation API

Dapr provides users with the ability to call other applications that are using Dapr with a unique named identifier (appId), or HTTP endpoints that are not using Dapr. This allows applications to interact with one another via named identifiers and puts the burden of service discovery on the Dapr runtime.

Invoke a method on a remote Dapr app

This endpoint lets you invoke a method in another Dapr enabled app.

HTTP Request

PATCH/POST/GET/PUT/DELETE http://localhost:<daprPort>/v1.0/invoke/<appID>/method/<method-name>

Invoke a method on a non-Dapr endpoint

This endpoint lets you invoke a method on a non-Dapr endpoint using an HTTPEndpoint resource name, or a Fully Qualified Domain Name (FQDN) URL.

HTTP Request

PATCH/POST/GET/PUT/DELETE http://localhost:<daprPort>/v1.0/invoke/<HTTPEndpoint name>/method/<method-name>

PATCH/POST/GET/PUT/DELETE http://localhost:<daprPort>/v1.0/invoke/<FQDN URL>/method/<method-name>

HTTP Response codes

When a service invokes another service with Dapr, the status code of the called service will be returned to the caller. If there’s a network error or other transient error, Dapr will return a 500 error with the detailed error message.

In case a user invokes Dapr over HTTP to talk to a gRPC enabled service, an error from the called gRPC service will return as 500 and a successful response will return as 200OK.

CodeDescription
XXXUpstream status returned
400Method name not given
403Invocation forbidden by access control
500Request failed

URL Parameters

ParameterDescription
daprPortthe Dapr port
appIDthe App ID associated with the remote app
HTTPEndpoint namethe HTTPEndpoint resource associated with the external endpoint
FQDN URLFully Qualified Domain Name URL to invoke on the external endpoint
method-namethe name of the method or url to invoke on the remote app

Note, all URL parameters are case-sensitive.

Request Contents

In the request you can pass along headers:

{
  "Content-Type": "application/json"
}

Within the body of the request place the data you want to send to the service:

{
  "arg1": 10,
  "arg2": 23,
  "operator": "+"
}

Request received by invoked service

Once your service code invokes a method in another Dapr enabled app or non-Dapr endpoint, Dapr sends the request, along with the headers and body, on the <method-name> endpoint.

The Dapr app or non-Dapr endpoint being invoked will need to be listening for and responding to requests on that endpoint.

Cross namespace invocation

On hosting platforms that support namespaces, Dapr app IDs conform to a valid FQDN format that includes the target namespace. For example, the following string contains the app ID (myApp) in addition to the namespace the app runs in (production).

myApp.production

Namespace supported platforms

  • Kubernetes

Examples

You can invoke the add method on the mathService service by sending the following:

curl http://localhost:3500/v1.0/invoke/mathService/method/add \
  -H "Content-Type: application/json"
  -d '{ "arg1": 10, "arg2": 23}'

The mathService service will need to be listening on the /add endpoint to receive and process the request.

For a Node app this would look like:

app.post('/add', (req, res) => {
  let args = req.body;
  const [operandOne, operandTwo] = [Number(args['arg1']), Number(args['arg2'])];

  let result = operandOne + operandTwo;
  res.send(result.toString());
});

app.listen(port, () => console.log(`Listening on port ${port}!`));

The response from the remote endpoint will be returned in the response body.

In case when your service listens on a more nested path (e.g. /api/v1/add), Dapr implements a full reverse proxy so you can append all the necessary path fragments to your request URL like this:

http://localhost:3500/v1.0/invoke/mathService/method/api/v1/add

In case you are invoking mathService on a different namespace, you can use the following URL:

http://localhost:3500/v1.0/invoke/mathService.testing/method/api/v1/add

In this URL, testing is the namespace that mathService is running in.

Headers in Service Invocation Requests

When Dapr invokes a service, it automatically adds the following headers to the request:

HeaderDescriptionExample
dapr-caller-app-idThe ID of the calling applicationmyapp
dapr-caller-namespaceThe namespace of the calling applicationproduction
dapr-callee-app-idThe ID of the called applicationmathService

These headers are available in both HTTP and gRPC service invocation requests.

Non-Dapr Endpoint Example

If the mathService service was a non-Dapr application, then it could be invoked using service invocation via an HTTPEndpoint, as well as a Fully Qualified Domain Name (FQDN) URL.

curl http://localhost:3500/v1.0/invoke/mathHTTPEndpoint/method/add \
  -H "Content-Type: application/json"
  -d '{ "arg1": 10, "arg2": 23}'

curl http://localhost:3500/v1.0/invoke/http://mathServiceURL.com/method/add \
  -H "Content-Type: application/json"
  -d '{ "arg1": 10, "arg2": 23}'

Next Steps

2 - Pub/sub API reference

Detailed documentation on the pub/sub API

Publish a message to a given topic

This endpoint lets you publish data to multiple consumers who are listening on a topic. Dapr guarantees At-Least-Once semantics for this endpoint.

HTTP Request

POST http://localhost:<daprPort>/v1.0/publish/<pubsubname>/<topic>[?<metadata>]

HTTP Response codes

CodeDescription
204Message delivered
403Message forbidden by access controls
404No pubsub name or topic given
500Delivery failed

URL Parameters

ParameterDescription
daprPortThe Dapr port
pubsubnameThe name of pubsub component
topicThe name of the topic
metadataQuery parameters for metadata as described below

Note, all URL parameters are case-sensitive.

curl -X POST http://localhost:3500/v1.0/publish/pubsubName/deathStarStatus \
  -H "Content-Type: application/json" \
 -d '{
       "status": "completed"
     }'

Headers

The Content-Type header tells Dapr which content type your data adheres to when constructing a CloudEvent envelope. The Content-Type header value populates the datacontenttype field in the CloudEvent.

Unless specified, Dapr assumes text/plain. If your content type is JSON, use a Content-Type header with the value of application/json.

If you want to send your own custom CloudEvent, use the application/cloudevents+json value for the Content-Type header.

Metadata

Metadata can be sent via query parameters in the request’s URL. It must be prefixed with metadata., as shown below.

ParameterDescription
metadata.ttlInSecondsThe number of seconds for the message to expire, as described here
metadata.rawPayloadBoolean to determine if Dapr should publish the event without wrapping it as CloudEvent, as described here

Additional metadata parameters are available based on each pubsub component.

Publish multiple messages to a given topic

This endpoint lets you publish multiple messages to consumers who are listening on a topic.

HTTP Request

POST http://localhost:<daprPort>/v1.0-alpha1/publish/bulk/<pubsubname>/<topic>[?<metadata>]

The request body should contain a JSON array of entries with:

  • Unique entry IDs
  • The event to publish
  • The content type of the event

If the content type for an event is not application/cloudevents+json, it is auto-wrapped as a CloudEvent (unless metadata.rawPayload is set to true).

Example:

curl -X POST http://localhost:3500/v1.0-alpha1/publish/bulk/pubsubName/deathStarStatus \
  -H 'Content-Type: application/json' \
  -d '[
        {
            "entryId": "ae6bf7c6-4af2-11ed-b878-0242ac120002",
            "event":  "first text message",
            "contentType": "text/plain"
        },
        {
            "entryId": "b1f40bd6-4af2-11ed-b878-0242ac120002",
            "event":  {
                "message": "second JSON message"   
            },
            "contentType": "application/json"
        },
      ]'

Headers

The Content-Type header should always be set to application/json since the request body is a JSON array.

URL Parameters

ParameterDescription
daprPortThe Dapr port
pubsubnameThe name of pub/sub component
topicThe name of the topic
metadataQuery parameters for metadata

Metadata

Metadata can be sent via query parameters in the request’s URL. It must be prefixed with metadata., as shown in the table below.

ParameterDescription
metadata.rawPayloadBoolean to determine if Dapr should publish the messages without wrapping them as CloudEvent.
metadata.maxBulkPubBytesMaximum bytes to publish in a bulk publish request.

HTTP Response

HTTP StatusDescription
204All messages delivered
400Pub/sub does not exist
403Forbidden by access controls
500At least one message failed to be delivered

In case of a 500 status code, the response body will contain a JSON object containing a list of entries that failed to be delivered. For example from our request above, if the entry with event "first text message" failed to be delivered, the response would contain its entry ID and an error message from the underlying pub/sub component.

{
  "failedEntries": [
    {
      "entryId": "ae6bf7c6-4af2-11ed-b878-0242ac120002",
      "error": "some error message"
    },
  ],
  "errorCode": "ERR_PUBSUB_PUBLISH_MESSAGE"
}

Optional Application (User Code) Routes

Provide a route for Dapr to discover topic subscriptions

Dapr will invoke the following endpoint on user code to discover topic subscriptions:

HTTP Request

GET http://localhost:<appPort>/dapr/subscribe

URL Parameters

ParameterDescription
appPortThe application port

HTTP Response body

A JSON-encoded array of strings.

Example:

[
  {
    "pubsubname": "pubsub",
    "topic": "newOrder",
    "routes": {
      "rules": [
        {
          "match": "event.type == order",
          "path": "/orders"
        }
      ]
      "default" : "/otherorders"
    },
    "metadata": {
      "rawPayload": "true"
    }
  }
]

Note, all subscription parameters are case-sensitive.

Metadata

Optionally, metadata can be sent via the request body.

ParameterDescription
rawPayloadboolean to subscribe to events that do not comply with CloudEvent specification, as described here

Provide route(s) for Dapr to deliver topic events

In order to deliver topic events, a POST call will be made to user code with the route specified in the subscription response. Under routes, you can provide rules that match a certain condition to a specific path when a message topic is received. You can also provide a default route for any rules that do not have a specific match.

The following example illustrates this point, considering a subscription for topic newOrder with route orders on port 3000: POST http://localhost:3000/orders

HTTP Request

POST http://localhost:<appPort>/<path>

Note, all URL parameters are case-sensitive.

URL Parameters

ParameterDescription
appPortThe application port
pathRoute path from the subscription configuration

Expected HTTP Response

An HTTP 2xx response denotes successful processing of message.

For richer response handling, a JSON-encoded payload body with the processing status can be sent:

{
  "status": "<status>"
}
StatusDescription
SUCCESSMessage is processed successfully
RETRYMessage to be retried by Dapr
DROPWarning is logged and message is dropped
OthersError, message to be retried by Dapr

Dapr assumes that a JSON-encoded payload response without status field or an empty payload responses with HTTP 2xx is a SUCCESS.

The HTTP response might be different from HTTP 2xx. The following are Dapr’s behavior in different HTTP statuses:

HTTP StatusDescription
2xxmessage is processed as per status in payload (SUCCESS if empty; ignored if invalid payload).
404error is logged and message is dropped
otherwarning is logged and message to be retried

Subscribe multiple messages from a given topic

This allows you to subscribe to multiple messages from a broker when listening to a topic.

In order to receive messages in a bulk manner for a topic subscription, the application:

  • Needs to opt for bulkSubscribe while sending list of topics to be subscribed to
  • Optionally, can configure maxMessagesCount and/or maxAwaitDurationMs Refer to the Send and receive messages in bulk guide for more details on how to opt-in.

Expected HTTP Response for Bulk Subscribe

An HTTP 2xx response denotes that entries (individual messages) inside this bulk message have been processed by the application and Dapr will now check each EntryId status. A JSON-encoded payload body with the processing status against each entry needs to be sent:

{
  "statuses": 
  [ 
    {
    "entryId": "<entryId1>",
    "status": "<status>"
    }, 
    {
    "entryId": "<entryId2>",
    "status": "<status>"
    } 
  ]
}

Note: If an EntryId status is not found by Dapr in a response received from the application, that entry’s status is considered RETRY.

StatusDescription
SUCCESSMessage is processed successfully
RETRYMessage to be retried by Dapr
DROPWarning is logged and message is dropped

The HTTP response might be different from HTTP 2xx. The following are Dapr’s behavior in different HTTP statuses:

HTTP StatusDescription
2xxmessage is processed as per status in payload.
404error is logged and all messages are dropped
otherwarning is logged and all messages to be retried

Message envelope

Dapr pub/sub adheres to version 1.0 of CloudEvents.

3 - Workflow API reference

Detailed documentation on the workflow API

Dapr provides users with the ability to interact with workflows through its built-in workflow engine, which is implemented using Dapr Actors. This workflow engine is accessed using the name dapr in API calls as the workflowComponentName.

Start workflow request

Start a workflow instance with the given name and optionally, an instance ID.

POST http://localhost:<daprPort>/v1.0/workflows/<workflowComponentName>/<workflowName>/start[?instanceID=<instanceID>]

Note that workflow instance IDs can only contain alphanumeric characters, underscores, and dashes.

URL parameters

ParameterDescription
workflowComponentNameUse dapr for Dapr Workflows
workflowNameIdentify the workflow type
instanceID(Optional) Unique value created for each run of a specific workflow

Request content

Any request content will be passed to the workflow as input. The Dapr API passes the content as-is without attempting to interpret it.

HTTP response codes

CodeDescription
202Accepted
400Request was malformed
500Request formatted correctly, error in dapr code

Response content

The API call will provide a response similar to this:

{
    "instanceID": "12345678"
}

Terminate workflow request

Terminate a running workflow instance with the given name and instance ID.

POST http://localhost:<daprPort>/v1.0/workflows/<workflowComponentName>/<instanceId>/terminate

URL parameters

ParameterDescription
workflowComponentNameUse dapr for Dapr Workflows
instanceIdUnique value created for each run of a specific workflow

HTTP response codes

CodeDescription
202Accepted
400Request was malformed
500Request formatted correctly, error in dapr code

Response content

This API does not return any content.

Raise Event request

For workflow components that support subscribing to external events, such as the Dapr Workflow engine, you can use the following “raise event” API to deliver a named event to a specific workflow instance.

POST http://localhost:<daprPort>/v1.0/workflows/<workflowComponentName>/<instanceID>/raiseEvent/<eventName>

URL parameters

ParameterDescription
workflowComponentNameUse dapr for Dapr Workflows
instanceIdUnique value created for each run of a specific workflow
eventNameThe name of the event to raise

HTTP response codes

CodeDescription
202Accepted
400Request was malformed
500Request formatted correctly, error in dapr code or underlying component

Response content

None.

Pause workflow request

Pause a running workflow instance.

POST http://localhost:<daprPort>/v1.0/workflows/<workflowComponentName>/<instanceId>/pause

URL parameters

ParameterDescription
workflowComponentNameUse dapr for Dapr Workflows
instanceIdUnique value created for each run of a specific workflow

HTTP response codes

CodeDescription
202Accepted
400Request was malformed
500Error in Dapr code or underlying component

Response content

None.

Resume workflow request

Resume a paused workflow instance.

POST http://localhost:<daprPort>/v1.0/workflows/<workflowComponentName>/<instanceId>/resume

URL parameters

ParameterDescription
workflowComponentNameUse dapr for Dapr Workflows
instanceIdUnique value created for each run of a specific workflow

HTTP response codes

CodeDescription
202Accepted
400Request was malformed
500Error in Dapr code

Response content

None.

Purge workflow request

Purge the workflow state from your state store with the workflow’s instance ID.

POST http://localhost:<daprPort>/v1.0/workflows/<workflowComponentName>/<instanceId>/purge

URL parameters

ParameterDescription
workflowComponentNameUse dapr for Dapr Workflows
instanceIdUnique value created for each run of a specific workflow

HTTP response codes

CodeDescription
202Accepted
400Request was malformed
500Error in Dapr code

Response content

None.

Get workflow request

Get information about a given workflow instance.

GET http://localhost:<daprPort>/v1.0/workflows/<workflowComponentName>/<instanceId>

URL parameters

ParameterDescription
workflowComponentNameUse dapr for Dapr Workflows
instanceIdUnique value created for each run of a specific workflow

HTTP response codes

CodeDescription
200OK
400Request was malformed
500Error in Dapr code

Response content

The API call will provide a JSON response similar to this:

{
  "createdAt": "2023-01-12T21:31:13Z",
  "instanceID": "12345678",
  "lastUpdatedAt": "2023-01-12T21:31:13Z",
  "properties": {
    "property1": "value1",
    "property2": "value2",
  },
  "runtimeStatus": "RUNNING",
 }
ParameterDescription
runtimeStatusThe status of the workflow instance. Values include: "RUNNING", "COMPLETED", "CONTINUED_AS_NEW", "FAILED", "CANCELED", "TERMINATED", "PENDING", "SUSPENDED"

Next Steps

4 - State management API reference

Detailed documentation on the state management API

Component file

A Dapr statestore.yaml component file has the following structure:

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: <NAME>
  namespace: <NAMESPACE>
spec:
  type: state.<TYPE>
  version: v1
  metadata:
  - name:<KEY>
    value:<VALUE>
  - name: <KEY>
    value: <VALUE>
SettingDescription
metadata.nameThe name of the state store.
spec/metadataAn open key value pair metadata that allows a binding to define connection properties.

Key scheme

Dapr state stores are key/value stores. To ensure data compatibility, Dapr requires these data stores follow a fixed key scheme. For general states, the key format is:

<App ID>||<state key>

For Actor states, the key format is:

<App ID>||<Actor type>||<Actor id>||<state key>

Save state

This endpoint lets you save an array of state objects.

HTTP Request

POST http://localhost:<daprPort>/v1.0/state/<storename>

URL Parameters

ParameterDescription
daprPortThe Dapr port
storenameThe metadata.name field in the user-configured statestore.yaml component file. Refer to the Dapr state store configuration structure mentioned above.

The optional request metadata is passed via URL query parameters. For example,

POST http://localhost:3500/v1.0/state/myStore?metadata.contentType=application/json

All URL parameters are case-sensitive.

Since || is a reserved string it cannot be used in the <state key> field.

Request Body

A JSON array of state objects. Each state object is comprised with the following fields:

FieldDescription
keyState key
valueState value, which can be any byte array
etag(optional) State ETag
metadata(optional) Additional key-value pairs to be passed to the state store
options(optional) State operation options; see state operation options

ETag format: Dapr runtime treats ETags as opaque strings. The exact ETag format is defined by the corresponding data store.

Metadata

Metadata can be sent via query parameters in the request’s URL. It must be prefixed with metadata., as shown below.

ParameterDescription
metadata.ttlInSecondsThe number of seconds for the message to expire, as described here

TTL: Only certain state stores support the TTL option, according the supported state stores.

HTTP Response

Response Codes

CodeDescription
204State saved
400State store is missing or misconfigured or malformed request
500Failed to save state

Response Body

None.

Example

curl -X POST http://localhost:3500/v1.0/state/starwars?metadata.contentType=application/json \
  -H "Content-Type: application/json" \
  -d '[
        {
          "key": "weapon",
          "value": "DeathStar",
          "etag": "1234"
        },
        {
          "key": "planet",
          "value": {
            "name": "Tatooine"
          }
        }
      ]'

Get state

This endpoint lets you get the state for a specific key.

HTTP Request

GET http://localhost:<daprPort>/v1.0/state/<storename>/<key>

URL Parameters

ParameterDescription
daprPortThe Dapr port
storenamemetadata.name field in the user-configured statestore.yaml component file. Refer to the Dapr state store configuration structure mentioned above.
keyThe key of the desired state
consistency(optional) Read consistency mode; see state operation options
metadata(optional) Metadata as query parameters to the state store

The optional request metadata is passed via URL query parameters. For example,

GET http://localhost:3500/v1.0/state/myStore/myKey?metadata.contentType=application/json

Note, all URL parameters are case-sensitive.

HTTP Response

Response Codes

CodeDescription
200Get state successful
204Key is not found
400State store is missing or misconfigured
500Get state failed

Response Headers

HeaderDescription
ETagETag of returned value

Response Body

JSON-encoded value

Example

curl http://localhost:3500/v1.0/state/starwars/planet?metadata.contentType=application/json

The above command returns the state:

{
  "name": "Tatooine"
}

To pass metadata as query parameter:

GET http://localhost:3500/v1.0/state/starwars/planet?metadata.partitionKey=mypartitionKey&metadata.contentType=application/json

Get bulk state

This endpoint lets you get a list of values for a given list of keys.

HTTP Request

POST/PUT http://localhost:<daprPort>/v1.0/state/<storename>/bulk

URL Parameters

ParameterDescription
daprPortThe Dapr port
storenamemetadata.name field in the user-configured statestore.yaml component file. Refer to the Dapr state store configuration structure mentioned above.
metadata(optional) Metadata as query parameters to the state store

The optional request metadata is passed via URL query parameters. For example,

POST/PUT http://localhost:3500/v1.0/state/myStore/bulk?metadata.partitionKey=mypartitionKey

Note, all URL parameters are case-sensitive.

HTTP Response

Response Codes

CodeDescription
200Get state successful
400State store is missing or misconfigured
500Get bulk state failed

Response Body

An array of JSON-encoded values

Example

curl http://localhost:3500/v1.0/state/myRedisStore/bulk \
  -H "Content-Type: application/json" \
  -d '{
          "keys": [ "key1", "key2" ],
          "parallelism": 10
      }'

The above command returns an array of key/value objects:

[
  {
    "key": "key1",
    "value": "value1",
    "etag": "1"
  },
  {
    "key": "key2",
    "value": "value2",
    "etag": "1"
  }
]

To pass metadata as query parameter:

POST http://localhost:3500/v1.0/state/myRedisStore/bulk?metadata.partitionKey=mypartitionKey

Delete state

This endpoint lets you delete the state for a specific key.

HTTP Request

DELETE http://localhost:<daprPort>/v1.0/state/<storename>/<key>

URL Parameters

ParameterDescription
daprPortThe Dapr port
storenamemetadata.name field in the user-configured statestore.yaml component file. Refer to the Dapr state store configuration structure mentioned above.
keyThe key of the desired state
concurrency(optional) Either first-write or last-write; see state operation options
consistency(optional) Either strong or eventual; see state operation options

The optional request metadata is passed via URL query parameters. For example,

DELETE http://localhost:3500/v1.0/state/myStore/myKey?metadata.contentType=application/json

Note, all URL parameters are case-sensitive.

Request Headers

HeaderDescription
If-Match(Optional) ETag associated with the key to be deleted

HTTP Response

Response Codes

CodeDescription
204Delete state successful
400State store is missing or misconfigured
500Delete state failed

Response Body

None.

Example

curl -X DELETE http://localhost:3500/v1.0/state/starwars/planet -H "If-Match: xxxxxxx"

Query state

This endpoint lets you query the key/value state.

HTTP Request

POST/PUT http://localhost:<daprPort>/v1.0-alpha1/state/<storename>/query

URL Parameters

ParameterDescription
daprPortThe Dapr port
storenamemetadata.name field in the user-configured statestore.yaml component file. Refer to the Dapr state store configuration structure mentioned above.
metadata(optional) Metadata as query parameters to the state store

The optional request metadata is passed via URL query parameters. For example,

POST http://localhost:3500/v1.0-alpha1/state/myStore/query?metadata.contentType=application/json

Note, all URL parameters are case-sensitive.

Response Codes

CodeDescription
200State query successful
400State store is missing or misconfigured
500State query failed

Response Body

An array of JSON-encoded values

Example

curl -X POST http://localhost:3500/v1.0-alpha1/state/myStore/query?metadata.contentType=application/json \
  -H "Content-Type: application/json" \
  -d '{
        "filter": {
          "OR": [
            {
              "EQ": { "person.org": "Dev Ops" }
            },
            {
              "AND": [
                {
                  "EQ": { "person.org": "Finance" }
                },
                {
                  "IN": { "state": [ "CA", "WA" ] }
                }
              ]
            }
          ]
        },
        "sort": [
          {
            "key": "state",
            "order": "DESC"
          },
          {
            "key": "person.id"
          }
        ],
        "page": {
          "limit": 3
        }
      }'

The above command returns an array of objects along with a token:

{
  "results": [
    {
      "key": "1",
      "data": {
        "person": {
          "org": "Dev Ops",
          "id": 1036
        },
        "city": "Seattle",
        "state": "WA"
      },
      "etag": "6f54ad94-dfb9-46f0-a371-e42d550adb7d"
    },
    {
      "key": "4",
      "data": {
        "person": {
          "org": "Dev Ops",
          "id": 1042
        },
        "city": "Spokane",
        "state": "WA"
      },
      "etag": "7415707b-82ce-44d0-bf15-6dc6305af3b1"
    },
    {
      "key": "10",
      "data": {
        "person": {
          "org": "Dev Ops",
          "id": 1054
        },
        "city": "New York",
        "state": "NY"
      },
      "etag": "26bbba88-9461-48d1-8a35-db07c374e5aa"
    }
  ],
  "token": "3"
}

To pass metadata as query parameter:

POST http://localhost:3500/v1.0-alpha1/state/myStore/query?metadata.partitionKey=mypartitionKey

State transactions

Persists the changes to the state store as a transactional operation.

This API depends on a state store component that supports transactions.

Refer to the state store component spec for a full, current list of state stores that support transactions.

HTTP Request

POST/PUT http://localhost:<daprPort>/v1.0/state/<storename>/transaction

HTTP Response Codes

CodeDescription
204Request successful
400State store is missing or misconfigured or malformed request
500Request failed

URL Parameters

ParameterDescription
daprPortThe Dapr port
storenamemetadata.name field in the user-configured statestore.yaml component file. Refer to the Dapr state store configuration structure mentioned above.

The optional request metadata is passed via URL query parameters. For example,

POST http://localhost:3500/v1.0/state/myStore/transaction?metadata.contentType=application/json

Note, all URL parameters are case-sensitive.

Request Body

FieldDescription
operationsA JSON array of state operation
metadata(optional) The metadata for the transaction that applies to all operations

All transactional databases implement the following required operations:

OperationDescription
upsertAdds or updates the value
deleteDeletes the value

Each operation has an associated request that is comprised of the following fields:

RequestDescription
keyState key
valueState value, which can be any byte array
etag(optional) State ETag
metadata(optional) Additional key-value pairs to be passed to the state store that apply for this operation
options(optional) State operation options; see state operation options

Examples

The example below shows an upsert operation for key1 and a delete operation for key2. This is applied to the partition named ‘planet’ in the state store. Both operations either succeed or fail in the transaction.

curl -X POST http://localhost:3500/v1.0/state/starwars/transaction \
  -H "Content-Type: application/json" \
  -d '{
        "operations": [
          {
            "operation": "upsert",
            "request": {
              "key": "key1",
              "value": "myData"
            }
          },
          {
            "operation": "delete",
            "request": {
              "key": "key2"
            }
          }
        ],
        "metadata": {
          "partitionKey": "planet"
        }
      }'

Configuring state store for actors

Actors don’t support multiple state stores and require a transactional state store to be used with Dapr. View which services currently implement the transactional state store interface.

Specify which state store to be used for actors with a true value for the property actorStateStore in the metadata section of the statestore.yaml component file. For example, the following components yaml will configure Redis to be used as the state store for Actors.

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: statestore
spec:
  type: state.redis
  version: v1
  metadata:
  - name: redisHost
    value: <redis host>
  - name: redisPassword
    value: ""
  - name: actorStateStore
    value: "true"

Optional behaviors

Key scheme

A Dapr-compatible state store shall use the following key scheme:

  • <App ID>||<state key> key format for general states
  • <App ID>||<Actor type>||<Actor id>||<state key> key format for Actor states.

Concurrency

Dapr uses Optimized Concurrency Control (OCC) with ETags. Dapr makes the following requirements optional on state stores:

  • A Dapr-compatible state store may support optimistic concurrency control using ETags. The store allows the update when an ETag:
    • Is associated with an save or delete request.
    • Matches the latest ETag in the database.
  • When ETag is missing in the write requests, the state store shall handle the requests in a last-write-wins fashion. This allows optimizations for high-throughput write scenarios, in which data contingency is low or has no negative effects.
  • A store shall always return ETags when returning states to callers.

Consistency

Dapr allows clients to attach a consistency hint to get, set, and delete operation. Dapr supports two consistency levels: strong and eventual.

Eventual Consistency

Dapr assumes data stores are eventually consistent by default. A state should:

  • For read requests, return data from any of the replicas.
  • For write requests, asynchronously replicate updates to configured quorum after acknowledging the update request.

Strong Consistency

When a strong consistency hint is attached, a state store should:

  • For read requests, return the most up-to-date data consistently across replicas.
  • For write/delete requests, synchronously replicate updated data to configured quorum before completing the write request.

Example: Complete options request example

The following is an example set request with a complete options definition:

curl -X POST http://localhost:3500/v1.0/state/starwars \
  -H "Content-Type: application/json" \
  -d '[
        {
          "key": "weapon",
          "value": "DeathStar",
          "etag": "xxxxx",
          "options": {
            "concurrency": "first-write",
            "consistency": "strong"
          }
        }
      ]'

Example: Working with ETags

The following is an example walk-through of an ETag usage when setting/deleting an object in a compatible state store. This sample defines Redis as statestore.

  1. Store an object in a state store:

    curl -X POST http://localhost:3500/v1.0/state/statestore \
        -H "Content-Type: application/json" \
        -d '[
                {
                    "key": "sampleData",
                    "value": "1"
                }
        ]'
    
  2. Get the object to find the ETag set automatically by the state store:

    curl http://localhost:3500/v1.0/state/statestore/sampleData -v
    * Connected to localhost (127.0.0.1) port 3500 (#0)
    > GET /v1.0/state/statestore/sampleData HTTP/1.1
    > Host: localhost:3500
    > User-Agent: curl/7.64.1
    > Accept: */*
    >
    < HTTP/1.1 200 OK
    < Server: fasthttp
    < Date: Sun, 14 Feb 2021 04:51:50 GMT
    < Content-Type: application/json
    < Content-Length: 3
    < Etag: 1
    < Traceparent: 00-3452582897d134dc9793a244025256b1-b58d8d773e4d661d-01
    <
    * Connection #0 to host localhost left intact
    "1"* Closing connection 0
    

    The returned ETag above was 1. If you send a new request to update or delete the data with the wrong ETag, it will return an error. Omitting the ETag will allow the request.

    # Update
    curl -X POST http://localhost:3500/v1.0/state/statestore \
        -H "Content-Type: application/json" \
        -d '[
                {
                    "key": "sampleData",
                    "value": "2",
                    "etag": "2"
                }
        ]'
    {"errorCode":"ERR_STATE_SAVE","message":"failed saving state in state store statestore: possible etag mismatch. error from state store: ERR Error running script (call to f_83e03ec05d6a3b6fb48483accf5e594597b6058f): @user_script:1: user_script:1: failed to set key nodeapp||sampleData"}
    
    # Delete
    curl -X DELETE -H 'If-Match: 5' http://localhost:3500/v1.0/state/statestore/sampleData
    {"errorCode":"ERR_STATE_DELETE","message":"failed deleting state with key sampleData: possible etag mismatch. error from state store: ERR Error running script (call to f_9b5da7354cb61e2ca9faff50f6c43b81c73c0b94): @user_script:1: user_script:1: failed to delete node
    app||sampleData"}
    
  3. Update or delete the object by simply matching the ETag in either the request body (update) or the If-Match header (delete). When the state is updated, it receives a new ETag that future updates or deletes will need to use.

    # Update
    curl -X POST http://localhost:3500/v1.0/state/statestore \
        -H "Content-Type: application/json" \
        -d '[
            {
                "key": "sampleData",
                "value": "2",
                "etag": "1"
            }
        ]'
    
    # Delete
    curl -X DELETE -H 'If-Match: 1' http://localhost:3500/v1.0/state/statestore/sampleData
    

Next Steps

5 - Bindings API reference

Detailed documentation on the bindings API

Dapr provides bi-directional binding capabilities for applications and a consistent approach to interacting with different cloud/on-premise services or systems. Developers can invoke output bindings using the Dapr API, and have the Dapr runtime trigger an application with input bindings.

Examples for bindings include Kafka, Rabbit MQ, Azure Event Hubs, AWS SQS, GCP Storage to name a few.

Bindings Structure

A Dapr Binding yaml file has the following structure:

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: <NAME>
  namespace: <NAMESPACE>
spec:
  type: bindings.<TYPE>
  version: v1
  metadata:
  - name: <NAME>
    value: <VALUE>

The metadata.name is the name of the binding.

If running self hosted locally, place this file in your components folder next to your state store and message queue yml configurations.

If running on kubernetes apply the component to your cluster.

Note: In production never place passwords or secrets within Dapr component files. For information on securely storing and retrieving secrets using secret stores refer to Setup Secret Store

Binding direction (optional)

In some scenarios, it would be useful to provide additional information to Dapr to indicate the direction supported by the binding component.

Providing the binding direction helps the Dapr sidecar avoid the "wait for the app to become ready" state, where it waits indefinitely for the application to become available. This decouples the lifecycle dependency between the Dapr sidecar and the application.

You can specify the direction field as part of the component’s metadata. The valid values for this field are:

  • "input"
  • "output"
  • "input, output"

Here a few scenarios when the "direction" metadata field could help:

  • When an application (detached from the sidecar) runs as a serverless workload and is scaled to zero, the "wait for the app to become ready" check done by the Dapr sidecar becomes pointless.

  • If the detached Dapr sidecar is scaled to zero and the application reaches the sidecar (before even starting an HTTP server), the "wait for the app to become ready" deadlocks the app and the sidecar into waiting for each other.

Example

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: kafkaevent
spec:
  type: bindings.kafka
  version: v1
  metadata:
  - name: brokers
    value: "http://localhost:5050"
  - name: topics
    value: "someTopic"
  - name: publishTopic
    value: "someTopic2"
  - name: consumerGroup
    value: "group1"
  - name: "direction"
    value: "input, output"

Invoking Service Code Through Input Bindings

A developer who wants to trigger their app using an input binding can listen on a POST http endpoint with the route name being the same as metadata.name.

On startup Dapr sends a OPTIONS request to the metadata.name endpoint and expects a different status code as NOT FOUND (404) if this application wants to subscribe to the binding.

The metadata section is an open key/value metadata pair that allows a binding to define connection properties, as well as custom properties unique to the component implementation.

Examples

For example, here’s how a Python application subscribes for events from Kafka using a Dapr API compliant platform. Note how the metadata.name value kafkaevent in the components matches the POST route name in the Python code.

Kafka Component

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: kafkaevent
spec:
  type: bindings.kafka
  version: v1
  metadata:
  - name: brokers
    value: "http://localhost:5050"
  - name: topics
    value: "someTopic"
  - name: publishTopic
    value: "someTopic2"
  - name: consumerGroup
    value: "group1"

Python Code

from flask import Flask
app = Flask(__name__)

@app.route("/kafkaevent", methods=['POST'])
def incoming():
    print("Hello from Kafka!", flush=True)

    return "Kafka Event Processed!"

Binding endpoints

Bindings are discovered from component yaml files. Dapr calls this endpoint on startup to ensure that app can handle this call. If the app doesn’t have the endpoint, Dapr ignores it.

HTTP Request

OPTIONS http://localhost:<appPort>/<name>

HTTP Response codes

CodeDescription
404Application does not want to bind to the binding
2xx or 405Application wants to bind to the binding

URL Parameters

ParameterDescription
appPortthe application port
namethe name of the binding

Note, all URL parameters are case-sensitive.

Binding payload

In order to deliver binding inputs, a POST call is made to user code with the name of the binding as the URL path.

HTTP Request

POST http://localhost:<appPort>/<name>

HTTP Response codes

CodeDescription
200Application processed the input binding successfully

URL Parameters

ParameterDescription
appPortthe application port
namethe name of the binding

Note, all URL parameters are case-sensitive.

HTTP Response body (optional)

Optionally, a response body can be used to directly bind input bindings with state stores or output bindings.

Example: Dapr stores stateDataToStore into a state store named “stateStore”. Dapr sends jsonObject to the output bindings named “storage” and “queue” in parallel. If concurrency is not set, it is sent out sequential (the example below shows these operations are done in parallel)

{
    "storeName": "stateStore",
    "state": stateDataToStore,

    "to": ['storage', 'queue'],
    "concurrency": "parallel",
    "data": jsonObject,
}

Invoking Output Bindings

This endpoint lets you invoke a Dapr output binding. Dapr bindings support various operations, such as create.

See the different specs on each binding to see the list of supported operations.

HTTP Request

POST/PUT http://localhost:<daprPort>/v1.0/bindings/<name>

HTTP Response codes

CodeDescription
200Request successful
204Empty Response
400Malformed request
500Request failed

Payload

The bindings endpoint receives the following JSON payload:

{
  "data": "",
  "metadata": {
    "": ""
  },
  "operation": ""
}

Note, all URL parameters are case-sensitive.

The data field takes any JSON serializable value and acts as the payload to be sent to the output binding. The metadata field is an array of key/value pairs and allows you to set binding specific metadata for each call. The operation field tells the Dapr binding which operation it should perform.

URL Parameters

ParameterDescription
daprPortthe Dapr port
namethe name of the output binding to invoke

Note, all URL parameters are case-sensitive.

Examples

curl -X POST http://localhost:3500/v1.0/bindings/myKafka \
  -H "Content-Type: application/json" \
  -d '{
        "data": {
          "message": "Hi"
        },
        "metadata": {
          "key": "redis-key-1"
        },
        "operation": "create"
      }'

Common metadata values

There are common metadata properties which are support across multiple binding components. The list below illustrates them:

PropertyDescriptionBinding definitionAvailable in
ttlInSecondsDefines the time to live in seconds for the messageIf set in the binding definition will cause all messages to have a default time to live. The message ttl overrides any value in the binding definition.RabbitMQ, Azure Service Bus, Azure Storage Queue

6 - Actors API reference

Detailed documentation on the actors API

Dapr provides native, cross-platform, and cross-language virtual actor capabilities. Besides the language specific SDKs, a developer can invoke an actor using the API endpoints below.

User service code calling Dapr

Invoke actor method

Invoke an actor method through Dapr.

HTTP Request

POST/GET/PUT/DELETE http://localhost:<daprPort>/v1.0/actors/<actorType>/<actorId>/method/<method>

HTTP Response Codes

CodeDescription
200Request successful
500Request failed
XXXStatus code from upstream call

URL Parameters

ParameterDescription
daprPortThe Dapr port.
actorTypeThe actor type.
actorIdThe actor ID.
methodThe name of the method to invoke.

Note, all URL parameters are case-sensitive.

Examples

Example of invoking a method on an actor:

curl -X POST http://localhost:3500/v1.0/actors/stormtrooper/50/method/shoot \
  -H "Content-Type: application/json"

You can provide the method parameters and values in the body of the request, for example in curl using -d "{\"param\":\"value\"}". Example of invoking a method on an actor that takes parameters:

curl -X POST http://localhost:3500/v1.0/actors/x-wing/33/method/fly \
  -H "Content-Type: application/json" \
  -d '{
        "destination": "Hoth"
      }'

or

curl -X POST http://localhost:3500/v1.0/actors/x-wing/33/method/fly \
  -H "Content-Type: application/json" \
  -d "{\"destination\":\"Hoth\"}"

The response (the method return) from the remote endpoint is returned in the request body.

Actor state transactions

Persists the change to the state for an actor as a multi-item transaction.

Note that this operation is dependant on a using state store component that supports multi-item transactions.

TTL

With the ActorStateTTL feature enabled, actor clients can set the ttlInSeconds field in the transaction metadata to have the state expire after that many seconds. If the ttlInSeconds field is not set, the state will not expire.

Keep in mind when building actor applications with this feature enabled; Currently, all actor SDKs will preserve the actor state in their local cache even after the state has expired. This means that the actor state will not be removed from the local cache if the TTL has expired until the actor is restarted or deactivated. This behaviour will be changed in a future release.

See the Dapr Community Call 80 recording for more details on actor state TTL.

HTTP Request

POST/PUT http://localhost:<daprPort>/v1.0/actors/<actorType>/<actorId>/state

HTTP Response Codes

CodeDescription
204Request successful
400Actor not found
500Request failed

URL Parameters

ParameterDescription
daprPortThe Dapr port.
actorTypeThe actor type.
actorIdThe actor ID.

Note, all URL parameters are case-sensitive.

Examples

Note, the following example uses the ttlInSeconds field, which requires the ActorStateTTL feature enabled.

curl -X POST http://localhost:3500/v1.0/actors/stormtrooper/50/state \
  -H "Content-Type: application/json" \
  -d '[
       {
         "operation": "upsert",
         "request": {
           "key": "key1",
           "value": "myData",
           "metadata": {
             "ttlInSeconds": "3600"
           }
         }
       },
       {
         "operation": "delete",
         "request": {
           "key": "key2"
         }
       }
      ]'

Get actor state

Gets the state for an actor using a specified key.

HTTP Request

GET http://localhost:<daprPort>/v1.0/actors/<actorType>/<actorId>/state/<key>

HTTP Response Codes

CodeDescription
200Request successful
204Key not found, and the response will be empty
400Actor not found
500Request failed

URL Parameters

ParameterDescription
daprPortThe Dapr port.
actorTypeThe actor type.
actorIdThe actor ID.
keyThe key for the state value.

Note, all URL parameters are case-sensitive.

Examples

curl http://localhost:3500/v1.0/actors/stormtrooper/50/state/location \
  -H "Content-Type: application/json"

The above command returns the state:

{
  "location": "Alderaan"
}

Create actor reminder

Creates a persistent reminder for an actor.

HTTP Request

POST/PUT http://localhost:<daprPort>/v1.0/actors/<actorType>/<actorId>/reminders/<name>

Reminder request body

A JSON object with the following fields:

FieldDescription
dueTimeSpecifies the time after which the reminder is invoked. Its format should be time.ParseDuration
periodSpecifies the period between different invocations. Its format should be time.ParseDuration or ISO 8601 duration format with optional recurrence.
ttlSets time at or interval after which the timer or reminder will be expired and deleted. Its format should be time.ParseDuration format, RFC3339 date format, or ISO 8601 duration format.
dataA string value and can be any related content. Content is returned when the reminder expires. For example this may be useful for returning a URL or anything related to the content.

period field supports time.Duration format and ISO 8601 format with some limitations. For period, only duration format of ISO 8601 duration Rn/PnYnMnWnDTnHnMnS is supported. Rn/ specifies that the reminder will be invoked n number of times.

  • n should be a positive integer greater than 0.
  • If certain values are 0, the period can be shortened; for example, 10 seconds can be specified in ISO 8601 duration as PT10S.

If Rn/ is not specified, the reminder will run an infinite number of times until deleted.

If only ttl and dueTime are set, the reminder will be accepted. However, only the dueTime takes effect. For example, the reminder triggers at dueTime, and ttl is ignored.

If ttl, dueTime, and period are set, the reminder first fires at dueTime, then repeatedly fires and expires according to period and ttl.

The following example specifies a dueTime of 3 seconds and a period of 7 seconds.

{
  "dueTime":"0h0m3s0ms",
  "period":"0h0m7s0ms"
}

A dueTime of 0 means to fire immediately. The following body means to fire immediately, then every 9 seconds.

{
  "dueTime":"0h0m0s0ms",
  "period":"0h0m9s0ms"
}

To configure the reminder to fire only once, the period should be set to empty string. The following specifies a dueTime of 3 seconds with a period of empty string, which means the reminder will fire in 3 seconds and then never fire again.

{
  "dueTime":"0h0m3s0ms",
  "period":""
}

When you specify the repetition number in both period and ttl, the timer/reminder is stopped when either condition is met. The following example has a timer with a period of 3 seconds (in ISO 8601 duration format) and a ttl of 20 seconds. This timer fires immediately after registration, then every 3 seconds after that for the duration of 20 seconds, after which it never fires again since the ttl was met

{
  "period":"PT3S",
  "ttl":"20s"
}

Need description for data.

{
  "data": "someData",
  "dueTime": "1m",
  "period": "20s"
}

HTTP Response Codes

CodeDescription
204Request successful
500Request failed
400Actor not found or malformed request

URL Parameters

ParameterDescription
daprPortThe Dapr port.
actorTypeThe actor type.
actorIdThe actor ID.
nameThe name of the reminder to create.

Note, all URL parameters are case-sensitive.

Examples

curl http://localhost:3500/v1.0/actors/stormtrooper/50/reminders/checkRebels \
  -H "Content-Type: application/json" \
-d '{
      "data": "someData",
      "dueTime": "1m",
      "period": "20s"
    }'

Get actor reminder

Gets a reminder for an actor.

HTTP Request

GET http://localhost:<daprPort>/v1.0/actors/<actorType>/<actorId>/reminders/<name>

HTTP Response Codes

CodeDescription
200Request successful
500Request failed

URL Parameters

ParameterDescription
daprPortThe Dapr port.
actorTypeThe actor type.
actorIdThe actor ID.
nameThe name of the reminder to get.

Note, all URL parameters are case-sensitive.

Examples

curl http://localhost:3500/v1.0/actors/stormtrooper/50/reminders/checkRebels \
  "Content-Type: application/json"

The above command returns the reminder:

{
  "dueTime": "1s",
  "period": "5s",
  "data": "0",
}

Delete actor reminder

Deletes a reminder for an actor.

HTTP Request

DELETE http://localhost:<daprPort>/v1.0/actors/<actorType>/<actorId>/reminders/<name>

HTTP Response Codes

CodeDescription
204Request successful
500Request failed

URL Parameters

ParameterDescription
daprPortThe Dapr port.
actorTypeThe actor type.
actorIdThe actor ID.
nameThe name of the reminder to delete.

Note, all URL parameters are case-sensitive.

Examples

curl -X DELETE http://localhost:3500/v1.0/actors/stormtrooper/50/reminders/checkRebels \
  -H "Content-Type: application/json"

Create actor timer

Creates a timer for an actor.

HTTP Request

POST/PUT http://localhost:<daprPort>/v1.0/actors/<actorType>/<actorId>/timers/<name>

Timer request body:

The format for the timer request body is the same as for actor reminders. For example:

The following specifies a dueTime of 3 seconds and a period of 7 seconds.

{
  "dueTime":"0h0m3s0ms",
  "period":"0h0m7s0ms"
}

A dueTime of 0 means to fire immediately. The following body means to fire immediately, then every 9 seconds.

{
  "dueTime":"0h0m0s0ms",
  "period":"0h0m9s0ms"
}

HTTP Response Codes

CodeDescription
204Request successful
500Request failed
400Actor not found or malformed request

URL Parameters

ParameterDescription
daprPortThe Dapr port.
actorTypeThe actor type.
actorIdThe actor ID.
nameThe name of the timer to create.

Note, all URL parameters are case-sensitive.

Examples

curl http://localhost:3500/v1.0/actors/stormtrooper/50/timers/checkRebels \
    -H "Content-Type: application/json" \
-d '{
      "data": "someData",
      "dueTime": "1m",
      "period": "20s",
      "callback": "myEventHandler"
    }'

Delete actor timer

Deletes a timer for an actor.

HTTP Request

DELETE http://localhost:<daprPort>/v1.0/actors/<actorType>/<actorId>/timers/<name>

HTTP Response Codes

CodeDescription
204Request successful
500Request failed

URL Parameters

ParameterDescription
daprPortThe Dapr port.
actorTypeThe actor type.
actorIdThe actor ID.
nameThe name of the timer to delete.

Note, all URL parameters are case-sensitive.

curl -X DELETE http://localhost:3500/v1.0/actors/stormtrooper/50/timers/checkRebels \
  -H "Content-Type: application/json"

Dapr calling to user service code

Get registered actors

Get the registered actors types for this app and the Dapr actor configuration settings.

HTTP Request

GET http://localhost:<appPort>/dapr/config

HTTP Response Codes

CodeDescription
200Request successful
500Request failed

URL Parameters

ParameterDescription
appPortThe application port.

Examples

Example of getting the registered actors:

curl -X GET http://localhost:3000/dapr/config \
  -H "Content-Type: application/json"

The above command returns the config (all fields are optional):

ParameterDescription
entitiesThe actor types this app supports.
actorIdleTimeoutSpecifies how long to wait before deactivating an idle actor. An actor is idle if no actor method calls and no reminders have fired on it.
actorScanIntervalA duration which specifies how often to scan for actors to deactivate idle actors. Actors that have been idle longer than the actorIdleTimeout will be deactivated.
drainOngoingCallTimeoutA duration used when in the process of draining rebalanced actors. This specifies how long to wait for the current active actor method to finish. If there is no current actor method call, this is ignored.
drainRebalancedActorsA bool. If true, Dapr will wait for drainOngoingCallTimeout to allow a current actor call to complete before trying to deactivate an actor. If false, do not wait.
reentrancyA configuration object that holds the options for actor reentrancy.
enabledA flag in the reentrancy configuration that is needed to enable reentrancy.
maxStackDepthA value in the reentrancy configuration that controls how many reentrant calls be made to the same actor.
entitiesConfigArray of entity configurations that allow per actor type settings. Any configuration defined here must have an entity that maps back into the root level entities.
{
  "entities":["actorType1", "actorType2"],
  "actorIdleTimeout": "1h",
  "actorScanInterval": "30s",
  "drainOngoingCallTimeout": "30s",
  "drainRebalancedActors": true,
  "reentrancy": {
    "enabled": true,
    "maxStackDepth": 32
  },
  "entitiesConfig": [
      {
          "entities": ["actorType1"],
          "actorIdleTimeout": "1m",
          "drainOngoingCallTimeout": "10s",
          "reentrancy": {
              "enabled": false
          }
      }
  ]
}

Deactivate actor

Deactivates an actor by persisting the instance of the actor to the state store with the specified actorId.

HTTP Request

DELETE http://localhost:<appPort>/actors/<actorType>/<actorId>

HTTP Response Codes

CodeDescription
200Request successful
400Actor not found
500Request failed

URL Parameters

ParameterDescription
appPortThe application port.
actorTypeThe actor type.
actorIdThe actor ID.

Note, all URL parameters are case-sensitive.

Examples

The following example deactivates the actor type stormtrooper that has actorId of 50.

curl -X DELETE http://localhost:3000/actors/stormtrooper/50 \
  -H "Content-Type: application/json"

Invoke actor method

Invokes a method for an actor with the specified methodName where:

  • Parameters to the method are passed in the body of the request message.
  • Return values are provided in the body of the response message.

If the actor is not already running, the app side should activate it.

HTTP Request

PUT http://localhost:<appPort>/actors/<actorType>/<actorId>/method/<methodName>

HTTP Response Codes

CodeDescription
200Request successful
500Request failed
404Actor not found

URL Parameters

ParameterDescription
appPortThe application port.
actorTypeThe actor type.
actorIdThe actor ID.
methodNameThe name of the method to invoke.

Note, all URL parameters are case-sensitive.

Examples

The following example calls the performAction method on the actor type stormtrooper that has actorId of 50.

curl -X POST http://localhost:3000/actors/stormtrooper/50/method/performAction \
  -H "Content-Type: application/json"

Invoke reminder

Invokes a reminder for an actor with the specified reminderName. If the actor is not already running, the app side should activate it.

HTTP Request

PUT http://localhost:<appPort>/actors/<actorType>/<actorId>/method/remind/<reminderName>

HTTP Response Codes

CodeDescription
200Request successful
500Request failed
404Actor not found

URL Parameters

ParameterDescription
appPortThe application port.
actorTypeThe actor type.
actorIdThe actor ID.
reminderNameThe name of the reminder to invoke.

Note, all URL parameters are case-sensitive.

Examples

The following example calls the checkRebels reminder method on the actor type stormtrooper that has actorId of 50.

curl -X POST http://localhost:3000/actors/stormtrooper/50/method/remind/checkRebels \
  -H "Content-Type: application/json"

Invoke timer

Invokes a timer for an actor with the specified timerName. If the actor is not already running, the app side should activate it.

HTTP Request

PUT http://localhost:<appPort>/actors/<actorType>/<actorId>/method/timer/<timerName>

HTTP Response Codes

CodeDescription
200Request successful
500Request failed
404Actor not found

URL Parameters

ParameterDescription
appPortThe application port.
actorTypeThe actor type.
actorIdThe actor ID.
timerNameThe name of the timer to invoke.

Note, all URL parameters are case-sensitive.

Examples

The following example calls the checkRebels timer method on the actor type stormtrooper that has actorId of 50.

curl -X POST http://localhost:3000/actors/stormtrooper/50/method/timer/checkRebels \
  -H "Content-Type: application/json"

Health check

Probes the application for a response to signal to Dapr that the app is healthy and running. Any response status code other than 200 will be considered an unhealthy response.

A response body is not required.

HTTP Request

GET http://localhost:<appPort>/healthz

HTTP Response Codes

CodeDescription
200App is healthy

URL Parameters

ParameterDescription
appPortThe application port.

Examples

Example of getting a health check response from the app:

curl -X GET http://localhost:3000/healthz \

Activating an Actor

Conceptually, activating an actor means creating the actor’s object and adding the actor to a tracking table. Review an example from the .NET SDK.

Querying actor state externally

To enable visibility into the state of an actor and allow for complex scenarios like state aggregation, Dapr saves actor state in external state stores, such as databases. As such, it is possible to query for an actor state externally by composing the correct key or query.

The state namespace created by Dapr for actors is composed of the following items:

  • App ID: Represents the unique ID given to the Dapr application.
  • Actor Type: Represents the type of the actor.
  • Actor ID: Represents the unique ID of the actor instance for an actor type.
  • Key: A key for the specific state value. An actor ID can hold multiple state keys.

The following example shows how to construct a key for the state of an actor instance under the myapp App ID namespace:

myapp||cat||hobbit||food

In the example above, we are getting the value for the state key food, for the actor ID hobbit with an actor type of cat, under the App ID namespace of myapp.

7 - Secrets API reference

Detailed documentation on the secrets API

Get Secret

This endpoint lets you get the value of a secret for a given secret store.

HTTP Request

GET http://localhost:<daprPort>/v1.0/secrets/<secret-store-name>/<name>

URL Parameters

ParameterDescription
daprPortthe Dapr port
secret-store-namethe name of the secret store to get the secret from
namethe name of the secret to get

Note, all URL parameters are case-sensitive.

Query Parameters

Some secret stores support optional, per-request metadata properties. Use query parameters to provide those properties. For example:

GET http://localhost:<daprPort>/v1.0/secrets/<secret-store-name>/<name>?metadata.version_id=15

Observe that not all secret stores support the same set of parameters. For example:

  • Hashicorp Vault, GCP Secret Manager and AWS Secret Manager support the version_id parameter
  • Only AWS Secret Manager supports the version_stage parameter
  • Only Kubernetes Secrets supports the namespace parameter Check each secret store’s documentation for the list of supported parameters.

HTTP Response

Response Body

If a secret store has support for multiple key-values in a secret, a JSON payload is returned with the key names as fields and their respective values.

In case of a secret store that only has name/value semantics, a JSON payload is returned with the name of the secret as the field and the value of the secret as the value.

See the classification of secret stores that support multiple keys in a secret and name/value semantics.

Response with multiple keys in a secret (eg. Kubernetes):
curl http://localhost:3500/v1.0/secrets/kubernetes/db-secret
{
  "key1": "value1",
  "key2": "value2"
}

The above example demonstrates a response from a secret store with multiple keys in a secret. Note that the secret name (db-secret) is not returned as part of the result.

Response from a secret store with name/value semantics:
curl http://localhost:3500/v1.0/secrets/vault/db-secret
{
  "db-secret": "value1"
}

The above example demonstrates a response from a secret store with name/value semantics. Compared to the result from a secret store with multiple keys in a secret, this result returns a single key-value pair, with the secret name (db-secret) returned as the key in the key-value pair.

Response Codes

CodeDescription
200OK
204Secret not found
400Secret store is missing or misconfigured
403Access denied
500Failed to get secret or no secret stores defined

Examples

curl http://localhost:3500/v1.0/secrets/mySecretStore/db-secret
curl http://localhost:3500/v1.0/secrets/myAwsSecretStore/db-secret?metadata.version_id=15&metadata.version_stage=production

Get Bulk Secret

This endpoint lets you get all the secrets in a secret store. It’s recommended to use token authentication for Dapr if configuring a secret store.

HTTP Request

GET http://localhost:<daprPort>/v1.0/secrets/<secret-store-name>/bulk

URL Parameters

ParameterDescription
daprPortthe Dapr port
secret-store-namethe name of the secret store to get the secret from

Note, all URL parameters are case-sensitive.

HTTP Response

Response Body

The returned response is a JSON containing the secrets. The JSON object will contain the secret names as fields and a map of secret keys and values as the field value.

Response with multiple secrets and multiple key / values in a secret (eg. Kubernetes):
curl http://localhost:3500/v1.0/secrets/kubernetes/bulk
{
    "secret1": {
        "key1": "value1",
        "key2": "value2"
    },
    "secret2": {
        "key3": "value3",
        "key4": "value4"
    }
}

Response Codes

CodeDescription
200OK
400Secret store is missing or misconfigured
403Access denied
500Failed to get secret or no secret stores defined

Examples

curl http://localhost:3500/v1.0/secrets/vault/bulk
{
    "key1": {
        "key1": "value1"
    },
    "key2": {
        "key2": "value2"
    }
}

8 - Configuration API reference

Detailed documentation on the configuration API

Get Configuration

This endpoint lets you get configuration from a store.

HTTP Request

GET http://localhost:<daprPort>/v1.0/configuration/<storename>

URL Parameters

ParameterDescription
daprPortThe Dapr port
storenameThe metadata.name field component file. Refer to the component spec

Query Parameters

If no query parameters are provided, all configuration items are returned. To specify the keys of the configuration items to get, use one or more key query parameters. For example:

GET http://localhost:<daprPort>/v1.0/configuration/mystore?key=config1&key=config2

To retrieve all configuration items:

GET http://localhost:<daprPort>/v1.0/configuration/mystore

Request Body

None

HTTP Response

Response Codes

CodeDescription
204Get operation successful
400Configuration store is missing or misconfigured or malformed request
500Failed to get configuration

Response Body

JSON-encoded value of key/value pairs for each configuration item.

Example

curl -X GET 'http://localhost:3500/v1.0/configuration/mystore?key=myConfigKey' 

The above command returns the following JSON:

{
    "myConfigKey": {
        "value":"myConfigValue"
    }
}

Subscribe Configuration

This endpoint lets you subscribe to configuration changes. Notifications happen when values are updated or deleted in the configuration store. This enables the application to react to configuration changes.

HTTP Request

GET http://localhost:<daprPort>/v1.0/configuration/<storename>/subscribe

URL Parameters

ParameterDescription
daprPortThe Dapr port
storenameThe metadata.name field component file. Refer to the component spec

Query Parameters

If no query parameters are provided, all configuration items are subscribed to. To specify the keys of the configuration items to subscribe to, use one or more key query parameters. For example:

GET http://localhost:<daprPort>/v1.0/configuration/mystore/subscribe?key=config1&key=config2

To subscribe to all changes:

GET http://localhost:<daprPort>/v1.0/configuration/mystore/subscribe

Request Body

None

HTTP Response

Response Codes

CodeDescription
200Subscribe operation successful
400Configuration store is missing or misconfigured or malformed request
500Failed to subscribe to configuration changes

Response Body

JSON-encoded value

Example

curl -X GET 'http://localhost:3500/v1.0/configuration/mystore/subscribe?key=myConfigKey' 

The above command returns the following JSON:

{
  "id": "<unique-id>"
}

The returned id parameter can be used to unsubscribe to the specific set of keys provided on the subscribe API call. This should be retained by the application.

Unsubscribe Configuration

This endpoint lets you unsubscribe to configuration changes.

HTTP Request

GET http://localhost:<daprPort>/v1.0/configuration/<storename>/<subscription-id>/unsubscribe

URL Parameters

ParameterDescription
daprPortThe Dapr port
storenameThe metadata.name field component file. Refer to the component spec
subscription-idThe value from the id field returned from the response of the subscribe endpoint

Query Parameters

None

Request Body

None

HTTP Response

Response Codes

CodeDescription
200Unsubscribe operation successful
400Configuration store is missing or misconfigured or malformed request
500Failed to unsubscribe to configuration changes

Response Body

{
    "ok" : true
}

Example

curl -X GET 'http://localhost:3500/v1.0-alpha1/configuration/mystore/bf3aa454-312d-403c-af95-6dec65058fa2/unsubscribe'

The above command returns the following JSON:

In case of successful operation:

{
  "ok": true
}

In case of unsuccessful operation:

{
  "ok": false,
  "message": "<dapr returned error message>"
}

Optional application (user code) routes

Provide a route for Dapr to send configuration changes

subscribing to configuration changes, Dapr invokes the application whenever a configuration item changes. Your application can have a /configuration endpoint that is called for all key updates that are subscribed to. The endpoint(s) can be made more specific for a given configuration store by adding /<store-name> and for a specific key by adding /<store-name>/<key> to the route.

HTTP Request

POST http://localhost:<appPort>/configuration/<store-name>/<key>

URL Parameters

ParameterDescription
appPortThe application port
storenameThe metadata.name field component file. Refer to the component spec
keyThe key subscribed to

Request Body

A list of configuration items for a given subscription id. Configuration items can have a version associated with them, which is returned in the notification.

{
    "id": "<subscription-id>",
    "items": [
        "key": "<key-of-configuration-item>",
        "value": "<new-value>",
        "version": "<version-of-item>"
    ]
}

Example

{
    "id": "bf3aa454-312d-403c-af95-6dec65058fa2",
    "items": [
        "key": "config-1",
        "value": "abcdefgh",
        "version": "1.1"
    ]
}

Next Steps

9 - Distributed Lock API reference

Detailed documentation on the distributed lock API

Lock

This endpoint lets you acquire a lock by supplying a named lock owner and the resource ID to lock.

HTTP Request

POST http://localhost:<daprPort>/v1.0-alpha1/lock/<storename>

URL Parameters

ParameterDescription
daprPortThe Dapr port
storenameThe metadata.name field component file. Refer to the component schema

Query Parameters

None

HTTP Response codes

CodeDescription
200Request successful
204Empty Response
400Malformed request
500Request failed

HTTP Request Body

The lock endpoint receives the following JSON payload:

{
    "resourceId": "",
    "lockOwner": "",
    "expiryInSeconds": 0
}
FieldDescription
resourceIdThe ID of the resource to lock. Can be any value
lockOwnerThe name of the lock owner. Should be set to a unique value per-request
expiryInSecondsThe time in seconds to hold the lock before it expires

HTTP Response Body

The lock endpoint returns the following payload:

{
    "success": true
}

Examples

curl -X POST http://localhost:3500/v1.0-alpha/lock/redisStore \
  -H "Content-Type: application/json" \
  -d '{
        "resourceId": "lock1",
        "lockOwner": "vader",
        "expiryInSeconds": 60
      }'

{
    "success": "true"
}

Unlock

This endpoint lets you unlock an existing lock based on the lock owner and resource Id

HTTP Request

POST http://localhost:<daprPort>/v1.0-alpha1/unlock/<storename>

URL Parameters

ParameterDescription
daprPortThe Dapr port
storenameThe metadata.name field component file. Refer to the component schema

Query Parameters

None

HTTP Response codes

CodeDescription
200Request successful
204Empty Response
400Malformed request
500Request failed

HTTP Request Body

The unlock endpoint receives the following JSON payload:

{
    "resourceId": "",
    "lockOwner": ""
}

HTTP Response Body

The unlock endpoint returns the following payload:

{
    "status": 0
}

The status field contains the following response codes:

CodeDescription
0Success
1Lock doesn’t exist
2Lock belongs to another owner
3Internal error

Examples

curl -X POST http://localhost:3500/v1.0-alpha/unlock/redisStore \
  -H "Content-Type: application/json" \
  -d '{
        "resourceId": "lock1",
        "lockOwner": "vader"
      }'

{
    "status": 0
}

10 - Health API reference

Detailed documentation on the health API

Dapr provides health checking probes that can be used as readiness or liveness of Dapr and for initialization readiness from SDKs.

Get Dapr health state

Gets the health state for Dapr by either:

  • Check for sidecar health
  • Check for the sidecar health, including component readiness, used during initialization.

Wait for Dapr HTTP port to become available

Wait for all components to be initialized, the Dapr HTTP port to be available and the app channel is initialized. For example, this endpoint is used with Kubernetes liveness probes.

HTTP Request

GET http://localhost:<daprPort>/v1.0/healthz

HTTP Response Codes

CodeDescription
204Dapr is healthy
500Dapr is not healthy

URL Parameters

ParameterDescription
daprPortThe Dapr port

Examples

curl -i http://localhost:3500/v1.0/healthz

Wait for specific health check against /outbound path

Wait for all components to be initialized, the Dapr HTTP port to be available, however the app channel is not yet established. This endpoint enables your application to perform calls on the Dapr sidecar APIs before the app channel is initalized, for example reading secrets with the secrets API. For example used in the Dapr SDKs waitForSidecar method (for example .NET and Java SDKs) to check sidecar is initialized correctly ready for any calls.

For example, the Java SDK and the .NET SDK uses this endpoint for initialization.

Currently, the v1.0/healthz/outbound endpoint is supported in the:

HTTP Request

GET http://localhost:<daprPort>/v1.0/healthz/outbound

HTTP Response Codes

CodeDescription
204Dapr is healthy
500Dapr is not healthy

URL Parameters

ParameterDescription
daprPortThe Dapr port

Examples

curl -i http://localhost:3500/v1.0/healthz/outbound

11 - Metadata API reference

Detailed documentation on the Metadata API

Dapr has a metadata API that returns information about the sidecar allowing runtime discoverability. The metadata endpoint returns the following information.

  • Runtime version
  • List of the loaded resources (components, subscriptions and HttpEndpoints)
  • Registered actor types
  • Features enabled
  • Application connection details
  • Custom, ephemeral attributes with information.

Metadata API

Components

Each loaded component provides its name, type and version and also information about supported features in the form of component capabilities. These features are available for the state store and binding component types. The table below shows the component type and the list of capabilities for a given version. This list might grow in future and only represents the capabilities of the loaded components.

Component typeCapabilities
State StoreETAG, TRANSACTION, ACTOR, QUERY_API
BindingINPUT_BINDING, OUTPUT_BINDING

HTTPEndpoints

Each loaded HttpEndpoint provides a name to easily identify the Dapr resource associated with the runtime.

Subscriptions

The metadata API returns a list of pub/sub subscriptions that the app has registered with the Dapr runtime. This includes the pub/sub name, topic, routes, dead letter topic, the subscription type, and the metadata associated with the subscription.

Enabled features

A list of features enabled via Configuration spec (including build-time overrides).

App connection details

The metadata API returns information related to Dapr’s connection to the app. This includes the app port, protocol, host, max concurrency, along with health check details.

Scheduler connection details

Information related to the connection to one or more scheduler hosts.

Attributes

The metadata API allows you to store additional attribute information in the format of key-value pairs. These are ephemeral in-memory and are not persisted if a sidecar is reloaded. This information should be added at the time of a sidecar creation (for example, after the application has started).

Get the Dapr sidecar information

Gets the Dapr sidecar information provided by the Metadata Endpoint.

Usecase:

The Get Metadata API can be used for discovering different capabilities supported by loaded components. It can help operators in determining which components to provision, for required capabilities.

HTTP Request

GET http://localhost:<daprPort>/v1.0/metadata

URL Parameters

ParameterDescription
daprPortThe Dapr port.

HTTP Response Codes

CodeDescription
200Metadata information returned
500Dapr could not return the metadata information

HTTP Response Body

Metadata API Response Object

NameTypeDescription
idstringApplication ID
runtimeVersionstringVersion of the Dapr runtime
enabledFeaturesstring[]List of features enabled by Dapr Configuration, see https://docs.dapr.io/operations/configuration/preview-features/
actorsMetadata API Response Registered Actor[]A json encoded array of registered actors metadata.
extended.attributeNamestringList of custom attributes as key-value pairs, where key is the attribute name.
componentsMetadata API Response Component[]A json encoded array of loaded components metadata.
httpEndpointsMetadata API Response HttpEndpoint[]A json encoded array of loaded HttpEndpoints metadata.
subscriptionsMetadata API Response Subscription[]A json encoded array of pub/sub subscriptions metadata.
appConnectionPropertiesMetadata API Response AppConnectionPropertiesA json encoded object of app connection properties.
schedulerMetadata API Response SchedulerA json encoded object of scheduler connection properties.

Metadata API Response Registered Actor

NameTypeDescription
typestringThe registered actor type.
countintegerNumber of actors running.

Metadata API Response Component

NameTypeDescription
namestringName of the component.
typestringComponent type.
versionstringComponent version.
capabilitiesarraySupported capabilities for this component type and version.

Metadata API Response HttpEndpoint

NameTypeDescription
namestringName of the HttpEndpoint.

Metadata API Response Subscription

NameTypeDescription
pubsubnamestringName of the pub/sub.
topicstringTopic name.
metadataobjectMetadata associated with the subscription.
rulesMetadata API Response Subscription Rules[]List of rules associated with the subscription.
deadLetterTopicstringDead letter topic name.
typestringType of the subscription, either DECLARATIVE, STREAMING or PROGRAMMATIC.

Metadata API Response Subscription Rules

NameTypeDescription
matchstringCEL expression to match the message, see https://docs.dapr.io/developing-applications/building-blocks/pubsub/howto-route-messages/#common-expression-language-cel
pathstringPath to route the message if the match expression is true.

Metadata API Response AppConnectionProperties

NameTypeDescription
portintegerPort on which the app is listening.
protocolstringProtocol used by the app.
channelAddressstringHost address on which the app is listening.
maxConcurrencyintegerMaximum number of concurrent requests the app can handle.
healthMetadata API Response AppConnectionProperties HealthHealth check details of the app.

Metadata API Response AppConnectionProperties Health

NameTypeDescription
healthCheckPathstringHealth check path, applicable for HTTP protocol.
healthProbeIntervalstringTime between each health probe, in go duration format.
healthProbeTimeoutstringTimeout for each health probe, in go duration format.
healthThresholdintegerMax number of failed health probes before the app is considered unhealthy.

Metadata API Response Scheduler

NameTypeDescription
connected_addressesstring[]List of strings representing the addresses of the conntected scheduler hosts.

Examples

curl http://localhost:3500/v1.0/metadata
{
  "id": "myApp",
  "runtimeVersion": "1.12.0",
  "enabledFeatures": [
    "ServiceInvocationStreaming"
  ],
  "actors": [
    {
      "type": "DemoActor"
    }
  ],
  "components": [
    {
      "name": "pubsub",
      "type": "pubsub.redis",
      "version": "v1"
    },
    {
      "name": "statestore",
      "type": "state.redis",
      "version": "v1",
      "capabilities": [
        "ETAG",
        "TRANSACTIONAL",
        "ACTOR"
      ]
    }
  ],
  "httpEndpoints": [
    {
      "name": "my-backend-api"
    }
  ],
  "subscriptions": [
    {
      "type": "DECLARATIVE",
      "pubsubname": "pubsub",
      "topic": "orders",
      "deadLetterTopic": "",
      "metadata": {
        "ttlInSeconds": "30"
      },
      "rules": [
          {
              "match": "%!s(<nil>)",
              "path": "orders"
          }
      ]
    }
  ],
  "extended": {
    "appCommand": "uvicorn --port 3000 demo_actor_service:app",
    "appPID": "98121",
    "cliPID": "98114",
    "daprRuntimeVersion": "1.12.0"
  },
  "appConnectionProperties": {
    "port": 3000,
    "protocol": "http",
    "channelAddress": "127.0.0.1",
    "health": {
      "healthProbeInterval": "5s",
      "healthProbeTimeout": "500ms",
      "healthThreshold": 3
    }
  },
  "scheduler": {
    "connected_addresses": [
      "10.244.0.47:50006",
      "10.244.0.48:50006",
      "10.244.0.49:50006"
    ]
  }
}

Add a custom label to the Dapr sidecar information

Adds a custom label to the Dapr sidecar information stored by the Metadata endpoint.

Usecase:

The metadata endpoint is, for example, used by the Dapr CLI when running dapr in self hosted mode to store the PID of the process hosting the sidecar and store the command used to run the application. Applications can also add attributes as keys after startup.

HTTP Request

PUT http://localhost:<daprPort>/v1.0/metadata/attributeName

URL Parameters

ParameterDescription
daprPortThe Dapr port.
attributeNameCustom attribute name. This is they key name in the key-value pair.

HTTP Request Body

In the request you need to pass the custom attribute value as RAW data:

{
  "Content-Type": "text/plain"
}

Within the body of the request place the custom attribute value you want to store:

attributeValue

HTTP Response Codes

CodeDescription
204Custom attribute added to the metadata information

Examples

Add a custom attribute to the metadata endpoint:

curl -X PUT -H "Content-Type: text/plain" --data "myDemoAttributeValue" http://localhost:3500/v1.0/metadata/myDemoAttribute

Get the metadata information to confirm your custom attribute was added:

{
  "id": "myApp",
  "runtimeVersion": "1.12.0",
  "enabledFeatures": [
    "ServiceInvocationStreaming"
  ],
  "actors": [
    {
      "type": "DemoActor"
    }
  ],
  "components": [
    {
      "name": "pubsub",
      "type": "pubsub.redis",
      "version": "v1"
    },
    {
      "name": "statestore",
      "type": "state.redis",
      "version": "v1",
      "capabilities": [
        "ETAG",
        "TRANSACTIONAL",
        "ACTOR"
      ]
    }
  ],
  "httpEndpoints": [
    {
      "name": "my-backend-api"
    }
  ],
  "subscriptions": [
    {
      "type": "PROGRAMMATIC",
      "pubsubname": "pubsub",
      "topic": "orders",
      "deadLetterTopic": "",
      "metadata": {
        "ttlInSeconds": "30"
      },
      "rules": [
          {
              "match": "%!s(<nil>)",
              "path": "orders"
          }
      ]
    }
  ],
  "extended": {
    "myDemoAttribute": "myDemoAttributeValue",
    "appCommand": "uvicorn --port 3000 demo_actor_service:app",
    "appPID": "98121",
    "cliPID": "98114",
    "daprRuntimeVersion": "1.12.0"
  },
  "appConnectionProperties": {
    "port": 3000,
    "protocol": "http",
    "channelAddress": "127.0.0.1",
    "health": {
      "healthProbeInterval": "5s",
      "healthProbeTimeout": "500ms",
      "healthThreshold": 3
    }
  },
  "scheduler": {
    "connected_addresses": [
      "10.244.0.47:50006",
      "10.244.0.48:50006",
      "10.244.0.49:50006"
    ]
  }
}

12 - Placement API reference

Detailed documentation on the Placement API

Dapr has an HTTP API /placement/state for Placement service that exposes placement table information. The API is exposed on the sidecar on the same port as the healthz. This is an unauthenticated endpoint, and is disabled by default.

To enable the placement metadata in self-hosted mode you can either setDAPR_PLACEMENT_METADATA_ENABLED environment variable or metadata-enabled command line args on the Placement service to true to. See how to run the Placement service in self-hosted mode.

If you are using Helm for deployment of the Placement service on Kubernetes then to enable the placement metadata, set dapr_placement.metadataEnabled to true.

Usecase

The placement table API can be used for retrieving the current placement table, which contains all the actors registered. This can be helpful for debugging and allows tools to extract and present information about actors.

HTTP Request

GET http://localhost:<healthzPort>/placement/state

HTTP Response Codes

CodeDescription
200Placement tables information returned
500Placement could not return the placement tables information

HTTP Response Body

Placement tables API Response Object

NameTypeDescription
tableVersionintThe placement table version
hostListActor Host Info[]A json array of registered actors host info.

Actor Host Info

NameTypeDescription
namestringThe host:port address of the actor.
appIdstringapp id.
actorTypesjson string arrayList of actor types it hosts.
updatedAttimestampTimestamp of the actor registered/updated.

Examples

 curl localhost:8080/placement/state
{
    "hostList": [{
            "name": "198.18.0.1:49347",
            "namespace": "ns1",
            "appId": "actor1",
            "actorTypes": ["testActorType1", "testActorType3"],
            "updatedAt": 1690274322325260000
        },
        {
            "name": "198.18.0.2:49347",
            "namespace": "ns2",
            "appId": "actor2",
            "actorTypes": ["testActorType2"],
            "updatedAt": 1690274322325260000
        },
        {
            "name": "198.18.0.3:49347",
            "namespace": "ns2",
            "appId": "actor2",
            "actorTypes": ["testActorType2"],
            "updatedAt": 1690274322325260000
        }
    ],
    "tableVersion": 1
}

13 - Cryptography API reference

Detailed documentation on the cryptography API

Dapr provides cross-platform and cross-language support for encryption and decryption support via the cryptography building block. Besides the language specific SDKs, a developer can invoke these capabilities using the HTTP API endpoints below.

The HTTP APIs are intended for development and testing only. For production scenarios, the use of the SDKs is strongly recommended as they implement the gRPC APIs providing higher performance and capability than the HTTP APIs.

Encrypt Payload

This endpoint lets you encrypt a value provided as a byte array using a specified key and crypto component.

HTTP Request

PUT http://localhost:<daprPort>/v1.0-alpha1/crypto/<crypto-store-name>/encrypt

URL Parameters

ParameterDescription
daprPortThe Dapr port
crypto-store-nameThe name of the crypto store to get the encryption key from

Note, all URL parameters are case-sensitive.

Headers

Additional encryption parameters are configured by setting headers with the appropriate values. The following table details the required and optional headers to set with every encryption request.

Header KeyDescriptionAllowed ValuesRequired
dapr-key-nameThe name of the key to use for the encryption operationYes
dapr-key-wrap-algorithmThe key wrap algorithm to useA256KW, A128CBC, A192CBC, RSA-OAEP-256Yes
dapr-omit-decryption-key-nameIf true, omits the decryption key name from header dapr-decryption-key-name from the output. If false, includes the specified decryption key name specified in header dapr-decryption-key-name.The following values will be accepted as true: y, yes, true, t, on, 1No
dapr-decryption-key-nameIf dapr-omit-decryption-key-name is true, this contains the name of the intended decryption key to include in the output.Required only if dapr-omit-decryption-key-name is true
dapr-data-encryption-cipherThe cipher to use for the encryption operationaes-gcm or chacha20-poly1305No

HTTP Response

Response Body

The response to an encryption request will have its content type header set to application/octet-stream as it returns an array of bytes with the encrypted payload.

Response Codes

CodeDescription
200OK
400Crypto provider not found
500Request formatted correctly, error in dapr code or underlying component

Examples

curl http://localhost:3500/v1.0-alpha1/crypto/myAzureKeyVault/encrypt \
    -X PUT \
    -H "dapr-key-name: myCryptoKey" \
    -H "dapr-key-wrap-algorithm: aes-gcm" \ 
    -H "Content-Type: application/octet-string" \ 
    --data-binary "\x68\x65\x6c\x6c\x6f\x20\x77\x6f\x72\x6c\x64"

The above command sends an array of UTF-8 encoded bytes representing “hello world” and would return a stream of 8-bit values in the response similar to the following containing the encrypted payload:

gAAAAABhZfZ0Ywz4dQX8y9J0Zl5v7w6Z7xq4jV3cW9o2l4pQ0YD1LdR0Zk7zIYi4n2Ll7t6f0Z4X7r8x9o6a8GyL0X1m9Q0Z0A==

Decrypt Payload

This endpoint lets you decrypt a value provided as a byte array using a specified key and crypto component.

HTTP Request

PUT curl http://localhost:3500/v1.0-alpha1/crypto/<crypto-store-name>/decrypt

URL Parameters

ParameterDescription
daprPortThe Dapr port
crypto-store-nameThe name of the crypto store to get the decryption key from

Note all parameters are case-sensitive.

Headers

Additional decryption parameters are configured by setting headers with the appropriate values. The following table details the required and optional headers to set with every decryption request.

Header KeyDescriptionRequired
dapr-key-nameThe name of the key to use for the decryption operation.Yes

HTTP Response

Response Body

The response to a decryption request will have its content type header to set application/octet-stream as it returns an array of bytes representing the decrypted payload.

Response Codes

CodeDescription
200OK
400Crypto provider not found
500Request formatted correctly, error in dapr code or underlying component

Examples

curl http://localhost:3500/v1.0-alpha1/crypto/myAzureKeyVault/decrypt \
    -X PUT
    -H "dapr-key-name: myCryptoKey"\
    -H "Content-Type: application/octet-stream" \
    --data-binary "gAAAAABhZfZ0Ywz4dQX8y9J0Zl5v7w6Z7xq4jV3cW9o2l4pQ0YD1LdR0Zk7zIYi4n2Ll7t6f0Z4X7r8x9o6a8GyL0X1m9Q0Z0A=="

The above command sends a base-64 encoded string of the encrypted message payload and would return a response with the content type header set to application/octet-stream returning the response body hello world.

hello world

14 - Jobs API reference

Detailed documentation on the jobs API

With the jobs API, you can schedule jobs and tasks in the future.

The HTTP APIs are intended for development and testing only. For production scenarios, the use of the SDKs is strongly recommended as they implement the gRPC APIs providing higher performance and capability than the HTTP APIs. This is because HTTP does JSON marshalling which can be expensive, while with gRPC, the data is transmitted over the wire and stored as-is being more performant.

Schedule a job

Schedule a job with a name. Jobs are scheduled based on the clock of the server where the Scheduler service is running. The timestamp is not converted to UTC. You can provide the timezone with the timestamp in RFC3339 format to specify which timezone you’d like the job to adhere to. If no timezone is provided, the server’s local time is used.

POST http://localhost:<daprPort>/v1.0-alpha1/jobs/<name>

URL parameters

ParameterDescription
nameName of the job you’re scheduling
dataA JSON serialized value or object.
scheduleAn optional schedule at which the job is to be run. Details of the format are below.
dueTimeAn optional time at which the job should be active, or the “one shot” time, if other scheduling type fields are not provided. Accepts a “point in time” string in the format of RFC3339, Go duration string (calculated from creation time), or non-repeating ISO8601.
repeatsAn optional number of times in which the job should be triggered. If not set, the job runs indefinitely or until expiration.
ttlAn optional time to live or expiration of the job. Accepts a “point in time” string in the format of RFC3339, Go duration string (calculated from job creation time), or non-repeating ISO8601.
overwriteA boolean value to specify if the job can overwrite an existing one with the same name. Default value is false
failure_policyAn optional failure policy for the job. Details of the format are below. If not set, the job is retried up to 3 times with a delay of 1 second between retries.

schedule

schedule accepts both systemd timer-style cron expressions, as well as human readable ‘@’ prefixed period strings, as defined below.

Systemd timer style cron accepts 6 fields:

secondsminuteshoursday of monthmonthday of week
0-590-590-231-311-12/jan-dec0-6/sun-sat
Example 1

“0 30 * * * *” - every hour on the half hour

Example 2

“0 15 3 * * *” - every day at 03:15

Period string expressions:

EntryDescriptionEquivalent To
@every Run every (e.g. ‘@every 1h30m’)N/A
@yearly (or @annually)Run once a year, midnight, Jan. 1st0 0 0 1 1 *
@monthlyRun once a month, midnight, first of month0 0 0 1 * *
@weeklyRun once a week, midnight on Sunday0 0 0 * * 0
@daily (or @midnight)Run once a day, midnight0 0 0 * * *
@hourlyRun once an hour, beginning of hour0 0 * * * *

failure_policy

failure_policy specifies how the job should handle failures.

It can be set to constant or drop.

  • The constant policy retries the job constantly with the following configuration options.
    • max_retries configures how many times the job should be retried. Defaults to retrying indefinitely. nil denotes unlimited retries, while 0 means the request will not be retried.
    • interval configures the delay between retries. Defaults to retrying immediately. Valid values are of the form 200ms, 15s, 2m, etc.
  • The drop policy drops the job after the first failure, without retrying.
Example 1
{
  //...
  "failure_policy": {
    "constant": {
      "max_retries": 3,
      "interval": "10s"
    }
  }
}
Example 2
{
  //...
  "failure_policy": {
    "drop": {}
  }
}

Request body

{
  "data": "some data",
  "dueTime": "30s"
}

HTTP response codes

CodeDescription
204Accepted
400Request was malformed
500Request formatted correctly, error in dapr code or Scheduler control plane service

Response content

The following example curl command creates a job, naming the job jobforjabba and specifying the schedule, repeats and the data.

$ curl -X POST \
  http://localhost:3500/v1.0-alpha1/jobs/jobforjabba \
  -H "Content-Type: application/json" \
  -d '{
        "data": "{\"value\":\"Running spice\"}",
        "schedule": "@every 1m",
        "repeats": 5
    }'

Get job data

Get a job from its name.

GET http://localhost:<daprPort>/v1.0-alpha1/jobs/<name>

URL parameters

ParameterDescription
nameName of the scheduled job you’re retrieving

HTTP response codes

CodeDescription
200Accepted
400Request was malformed
500Request formatted correctly, Job doesn’t exist or error in dapr code or Scheduler control plane service

Response content

After running the following example curl command, the returned response is JSON containing the name of the job, the dueTime, and the data.

$ curl -X GET http://localhost:3500/v1.0-alpha1/jobs/jobforjabba -H "Content-Type: application/json"
{
  "name": "jobforjabba",
  "schedule": "@every 1m",
  "repeats": 5,
  "data": 123
}

Delete a job

Delete a named job.

DELETE http://localhost:<daprPort>/v1.0-alpha1/jobs/<name>

URL parameters

ParameterDescription
nameName of the job you’re deleting

HTTP response codes

CodeDescription
204Accepted
400Request was malformed
500Request formatted correctly, error in dapr code or Scheduler control plane service

Response content

In the following example curl command, the job named test1 with app-id sub will be deleted

$ curl -X DELETE http://localhost:3500/v1.0-alpha1/jobs/jobforjabba -H "Content-Type: application/json"

Next steps

Jobs API overview

15 - Conversation API reference

Detailed documentation on the conversation API

Dapr provides an API to interact with Large Language Models (LLMs) and enables critical performance and security functionality with features like prompt caching and PII data obfuscation.

Converse

This endpoint lets you converse with LLMs.

POST http://localhost:<daprPort>/v1.0-alpha1/conversation/<llm-name>/converse

URL parameters

ParameterDescription
llm-nameThe name of the LLM component. See a list of all available conversation components.

Request body

FieldDescription
inputsInputs for the conversation. Multiple inputs at one time are supported. Required
cacheTTLA time-to-live value for a prompt cache to expire. Uses Golang duration format. Optional
scrubPIIA boolean value to enable obfuscation of sensitive information returning from the LLM. Set this value if all PII (across contents) in the request needs to be scrubbed. Optional
temperatureA float value to control the temperature of the model. Used to optimize for consistency and creativity. Optional
metadataMetadata passed to conversation components. Optional

Input body

FieldDescription
contentThe message content to send to the LLM. Required
roleThe role for the LLM to assume. Possible values: ‘user’, ’tool’, ‘assistant’
scrubPIIA boolean value to enable obfuscation of sensitive information present in the content field. Set this value if PII for this specific content needs to be scrubbed exclusively. Optional

Request content example

REQUEST = {
  "inputs": [
    {
      "content": "What is Dapr?",
      "role": "user", // Optional
      "scrubPII": "true", // Optional. Will obfuscate any sensitive information found in the content field
    },
  ],
  "cacheTTL": "10m", // Optional
  "scrubPII": "true", // Optional. Will obfuscate any sensitive information returning from the LLM
  "temperature": 0.5 // Optional. Optimizes for consistency (0) or creativity (1)
}

HTTP response codes

CodeDescription
202Accepted
400Request was malformed
500Request formatted correctly, error in Dapr code or underlying component

Response content

RESPONSE  = {
  "outputs": {
    {
       "result": "Dapr is distribution application runtime ...",
       "parameters": {},
    },
    {
       "result": "Dapr can help developers ...",
       "parameters": {},
    }
  },
}

Next steps