How-To: Invoke services using HTTP

Call between services using service invocation

This article demonstrates how to deploy services each with an unique application ID for other services to discover and call endpoints on them using service invocation over HTTP.

Diagram showing service invocation of example service

Note

If you haven’t already, try out the service invocation quickstart for a quick walk-through on how to use the service invocation API.

Choose an ID for your service

Dapr allows you to assign a global, unique ID for your app. This ID encapsulates the state for your application, regardless of the number of instances it may have.

  1. dapr run --app-id checkout --app-protocol http --dapr-http-port 3500 -- python3 checkout/app.py
  2. dapr run --app-id order-processor --app-port 8001 --app-protocol http --dapr-http-port 3501 -- python3 order-processor/app.py

If your app uses a TLS, you can tell Dapr to invoke your app over a TLS connection by setting --app-protocol https:

  1. dapr run --app-id checkout --app-protocol https --dapr-http-port 3500 -- python3 checkout/app.py
  2. dapr run --app-id order-processor --app-port 8001 --app-protocol https --dapr-http-port 3501 -- python3 order-processor/app.py
  1. dapr run --app-id checkout --app-protocol http --dapr-http-port 3500 -- npm start
  2. dapr run --app-id order-processor --app-port 5001 --app-protocol http --dapr-http-port 3501 -- npm start

If your app uses a TLS, you can tell Dapr to invoke your app over a TLS connection by setting --app-protocol https:

  1. dapr run --app-id checkout --dapr-http-port 3500 --app-protocol https -- npm start
  2. dapr run --app-id order-processor --app-port 5001 --dapr-http-port 3501 --app-protocol https -- npm start
  1. dapr run --app-id checkout --app-protocol http --dapr-http-port 3500 -- dotnet run
  2. dapr run --app-id order-processor --app-port 7001 --app-protocol http --dapr-http-port 3501 -- dotnet run

If your app uses a TLS, you can tell Dapr to invoke your app over a TLS connection by setting --app-protocol https:

  1. dapr run --app-id checkout --dapr-http-port 3500 --app-protocol https -- dotnet run
  2. dapr run --app-id order-processor --app-port 7001 --dapr-http-port 3501 --app-protocol https -- dotnet run
  1. dapr run --app-id checkout --app-protocol http --dapr-http-port 3500 -- java -jar target/CheckoutService-0.0.1-SNAPSHOT.jar
  2. dapr run --app-id order-processor --app-port 9001 --app-protocol http --dapr-http-port 3501 -- java -jar target/OrderProcessingService-0.0.1-SNAPSHOT.jar

If your app uses a TLS, you can tell Dapr to invoke your app over a TLS connection by setting --app-protocol https:

  1. dapr run --app-id checkout --dapr-http-port 3500 --app-protocol https -- java -jar target/CheckoutService-0.0.1-SNAPSHOT.jar
  2. dapr run --app-id order-processor --app-port 9001 --dapr-http-port 3501 --app-protocol https -- java -jar target/OrderProcessingService-0.0.1-SNAPSHOT.jar
  1. dapr run --app-id checkout --dapr-http-port 3500 -- go run .
  2. dapr run --app-id order-processor --app-port 6006 --app-protocol http --dapr-http-port 3501 -- go run .

If your app uses a TLS, you can tell Dapr to invoke your app over a TLS connection by setting --app-protocol https:

  1. dapr run --app-id checkout --dapr-http-port 3500 --app-protocol https -- go run .
  2. dapr run --app-id order-processor --app-port 6006 --dapr-http-port 3501 --app-protocol https -- go run .

Set an app-id when deploying to Kubernetes

In Kubernetes, set the dapr.io/app-id annotation on your pod:

  1. apiVersion: apps/v1
  2. kind: Deployment
  3. metadata:
  4. name: <language>-app
  5. namespace: default
  6. labels:
  7. app: <language>-app
  8. spec:
  9. replicas: 1
  10. selector:
  11. matchLabels:
  12. app: <language>-app
  13. template:
  14. metadata:
  15. labels:
  16. app: <language>-app
  17. annotations:
  18. dapr.io/enabled: "true"
  19. dapr.io/app-id: "order-processor"
  20. dapr.io/app-port: "6001"
  21. ...

If your app uses a TLS connection, you can tell Dapr to invoke your app over TLS with the app-protocol: "https" annotation (full list here). Note that Dapr does not validate TLS certificates presented by the app.

Invoke the service

To invoke an application using Dapr, you can use the invoke API on any Dapr instance. The sidecar programming model encourages each application to interact with its own instance of Dapr. The Dapr sidecars discover and communicate with one another.

Below are code examples that leverage Dapr SDKs for service invocation.

  1. #dependencies
  2. import random
  3. from time import sleep
  4. import logging
  5. import requests
  6. #code
  7. logging.basicConfig(level = logging.INFO)
  8. while True:
  9. sleep(random.randrange(50, 5000) / 1000)
  10. orderId = random.randint(1, 1000)
  11. #Invoke a service
  12. result = requests.post(
  13. url='%s/orders' % (base_url),
  14. data=json.dumps(order),
  15. headers=headers
  16. )
  17. logging.basicConfig(level = logging.INFO)
  18. logging.info('Order requested: ' + str(orderId))
  19. logging.info('Result: ' + str(result))
  1. //dependencies
  2. import axios from "axios";
  3. //code
  4. const daprHost = "127.0.0.1";
  5. var main = function() {
  6. for(var i=0;i<10;i++) {
  7. sleep(5000);
  8. var orderId = Math.floor(Math.random() * (1000 - 1) + 1);
  9. start(orderId).catch((e) => {
  10. console.error(e);
  11. process.exit(1);
  12. });
  13. }
  14. }
  15. //Invoke a service
  16. const result = await axios.post('order-processor' , "orders/" + orderId , axiosConfig);
  17. console.log("Order requested: " + orderId);
  18. console.log("Result: " + result.config.data);
  19. function sleep(ms) {
  20. return new Promise(resolve => setTimeout(resolve, ms));
  21. }
  22. main();
  1. //dependencies
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Net.Http;
  5. using System.Net.Http.Headers;
  6. using System.Threading.Tasks;
  7. using Microsoft.AspNetCore.Mvc;
  8. using System.Threading;
  9. //code
  10. namespace EventService
  11. {
  12. class Program
  13. {
  14. static async Task Main(string[] args)
  15. {
  16. while(true) {
  17. await Task.Delay(5000)
  18. var random = new Random();
  19. var orderId = random.Next(1,1000);
  20. //Using Dapr SDK to invoke a method
  21. var order = new Order("1");
  22. var orderJson = JsonSerializer.Serialize<Order>(order);
  23. var content = new StringContent(orderJson, Encoding.UTF8, "application/json");
  24. var httpClient = DaprClient.CreateInvokeHttpClient();
  25. await httpClient.PostAsJsonAsync($"http://order-processor/orders", content);
  26. Console.WriteLine("Order requested: " + orderId);
  27. Console.WriteLine("Result: " + result);
  28. }
  29. }
  30. }
  31. }
  1. //dependencies
  2. import java.io.IOException;
  3. import java.net.URI;
  4. import java.net.http.HttpClient;
  5. import java.net.http.HttpRequest;
  6. import java.net.http.HttpResponse;
  7. import java.time.Duration;
  8. import java.util.HashMap;
  9. import java.util.Map;
  10. import java.util.Random;
  11. import java.util.concurrent.TimeUnit;
  12. //code
  13. @SpringBootApplication
  14. public class CheckoutServiceApplication {
  15. private static final HttpClient httpClient = HttpClient.newBuilder()
  16. .version(HttpClient.Version.HTTP_2)
  17. .connectTimeout(Duration.ofSeconds(10))
  18. .build();
  19. public static void main(String[] args) throws InterruptedException, IOException {
  20. while (true) {
  21. TimeUnit.MILLISECONDS.sleep(5000);
  22. Random random = new Random();
  23. int orderId = random.nextInt(1000 - 1) + 1;
  24. // Create a Map to represent the request body
  25. Map<String, Object> requestBody = new HashMap<>();
  26. requestBody.put("orderId", orderId);
  27. // Add other fields to the requestBody Map as needed
  28. HttpRequest request = HttpRequest.newBuilder()
  29. .POST(HttpRequest.BodyPublishers.ofString(new JSONObject(requestBody).toString()))
  30. .uri(URI.create(dapr_url))
  31. .header("Content-Type", "application/json")
  32. .header("dapr-app-id", "order-processor")
  33. .build();
  34. HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
  35. System.out.println("Order passed: " + orderId);
  36. TimeUnit.MILLISECONDS.sleep(1000);
  37. log.info("Order requested: " + orderId);
  38. log.info("Result: " + response.body());
  39. }
  40. }
  41. }
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "log"
  6. "math/rand"
  7. "net/http"
  8. "os"
  9. "time"
  10. )
  11. func main() {
  12. daprHttpPort := os.Getenv("DAPR_HTTP_PORT")
  13. if daprHttpPort == "" {
  14. daprHttpPort = "3500"
  15. }
  16. client := &http.Client{
  17. Timeout: 15 * time.Second,
  18. }
  19. for i := 0; i < 10; i++ {
  20. time.Sleep(5000)
  21. orderId := rand.Intn(1000-1) + 1
  22. url := fmt.Sprintf("http://localhost:%s/checkout/%v", daprHttpPort, orderId)
  23. req, err := http.NewRequest(http.MethodGet, url, nil)
  24. if err != nil {
  25. panic(err)
  26. }
  27. // Adding target app id as part of the header
  28. req.Header.Add("dapr-app-id", "order-processor")
  29. // Invoking a service
  30. resp, err := client.Do(req)
  31. if err != nil {
  32. log.Fatal(err.Error())
  33. }
  34. b, err := io.ReadAll(resp.Body)
  35. if err != nil {
  36. panic(err)
  37. }
  38. fmt.Println(string(b))
  39. }
  40. }

Additional URL formats

To invoke a ‘GET’ endpoint:

  1. curl http://localhost:3602/v1.0/invoke/checkout/method/checkout/100

To avoid changing URL paths as much as possible, Dapr provides the following ways to call the service invocation API:

  1. Change the address in the URL to localhost:<dapr-http-port>.
  2. Add a dapr-app-id header to specify the ID of the target service, or alternatively pass the ID via HTTP Basic Auth: http://dapr-app-id:<service-id>@localhost:3602/path.

For example, the following command:

  1. curl http://localhost:3602/v1.0/invoke/checkout/method/checkout/100

is equivalent to:

  1. curl -H 'dapr-app-id: checkout' 'http://localhost:3602/checkout/100' -X POST

or:

  1. curl 'http://dapr-app-id:checkout@localhost:3602/checkout/100' -X POST

Using CLI:

  1. dapr invoke --app-id checkout --method checkout/100

Namespaces

When running on namespace supported platforms, you include the namespace of the target app in the app ID. For example, following the <app>.<namespace> format, use checkout.production.

Using this example, invoking the service with a namespace would look like:

  1. curl http://localhost:3602/v1.0/invoke/checkout.production/method/checkout/100 -X POST

See the Cross namespace API spec for more information on namespaces.

View traces and logs

Our example above showed you how to directly invoke a different service running locally or in Kubernetes. Dapr:

  • Outputs metrics, tracing, and logging information,
  • Allows you to visualize a call graph between services and log errors, and
  • Optionally, log the payload body.

For more information on tracing and logs, see the observability article.

Last modified October 12, 2023: Update config.toml (#3826) (0ffc2e7)