diff --git a/examples/invoke-http/README.md b/examples/invoke-http/README.md new file mode 100644 index 00000000..08e8738e --- /dev/null +++ b/examples/invoke-http/README.md @@ -0,0 +1,75 @@ +# Example - Invoke a service + +This example utilizes a receiver and a caller for the `invoke_method` functionality. + +> **Note:** Make sure to use the latest proto bindings + +## Pre-requisites + +- [Dapr CLI and initialized environment](https://docs.dapr.io/getting-started) +- [Install Python 3.8+](https://www.python.org/downloads/) + +### Install requirements + +You can install dapr SDK package using pip command: + + + +```sh +pip3 install dapr Flask +``` + + + +## Run the example + +To run this example, the following code can be utilized: + +Start the receiver: + + +```bash +dapr run --app-id=invoke-receiver --app-port=8088 --app-protocol http -- python3 invoke-receiver.py +``` + + +Start the caller: + + +```bash +dapr run --app-id=invoke-caller -- python3 invoke-caller.py +``` + + +## Cleanup + + + +```bash +dapr stop --app-id invoke-receiver +``` + + \ No newline at end of file diff --git a/examples/invoke-http/invoke-caller.py b/examples/invoke-http/invoke-caller.py index 6e2c3120..ebc5876b 100644 --- a/examples/invoke-http/invoke-caller.py +++ b/examples/invoke-http/invoke-caller.py @@ -6,18 +6,29 @@ with DaprClient() as d: req_data = {'id': 1, 'message': 'hello world'} - while True: - # Create a typed message with content type and body - resp = d.invoke_method( + # First message: success + # Create a typed message with content type and body + resp1 = d.invoke_method( + 'invoke-receiver', + 'my-method', + http_verb='POST', + data=json.dumps(req_data), + ) + + # Print the response + print(resp1.content_type, flush=True) + print(resp1.text(), flush=True) + print(str(resp1.status_code), flush=True) + + # Second message: error + req_data = {'id': 2, 'message': 'hello world'} + try: + resp2 = d.invoke_method( 'invoke-receiver', - 'my-method', + 'my-method-err', http_verb='POST', data=json.dumps(req_data), ) - - # Print the response - print(resp.content_type, flush=True) - print(resp.text(), flush=True) - print(str(resp.status_code), flush=True) - - time.sleep(2) + except Exception as e: + print(e._message, flush=True) + print(e._error_code, flush=True) diff --git a/examples/invoke-http/invoke-receiver.py b/examples/invoke-http/invoke-receiver.py index 95ac3192..8609464a 100644 --- a/examples/invoke-http/invoke-receiver.py +++ b/examples/invoke-http/invoke-receiver.py @@ -12,4 +12,13 @@ def getOrder(): return json.dumps({'success': True}), 200, {'ContentType': 'application/json'} +@app.route('/my-method-err', methods=['POST']) +def getOrderErr(): + data = request.json + print('Order error : ' + json.dumps(data), flush=True) + resp = {'message': 'error occurred', 'errorCode': 'MY_CODE'} + return json.dumps(resp), 503, {'ContentType': 'application/json'} + + +print('Starting Flask app on port 8088...', flush=True) app.run(port=8088)