Quickstart: Create an App showing GitHub star count with Azure Functions and SignalR Service using Python
Azure SignalR Service lets you easily add real-time functionality to your application. Azure Functions is a serverless platform that lets you run your code without managing any infrastructure. In this quickstart, learn how to use SignalR Service and Azure Functions to build a serverless application with Python to broadcast messages to clients.
Note
You can get all codes mentioned in the article from GitHub
Prerequisites
This quickstart can be run on macOS, Windows, or Linux.
Make sure you have a code editor such as Visual Studio Code installed.
Install the Azure Functions Core Tools (version 2.7.1505 or higher) to run Python Azure Function apps locally.
Azure Functions requires Python 3.6+. (See Supported Python versions)
If you don't have an Azure subscription, create a free account before you begin.
Having issues? Try the troubleshooting guide or let us know.
Log in to Azure
Sign in to the Azure portal at https://portal.azure.com/ with your Azure account.
Having issues? Try the troubleshooting guide or let us know.
Create an Azure SignalR Service instance
Your application will connect to a SignalR Service instance in Azure.
Select the New button found on the upper left-hand corner of the Azure portal. In the New screen, type SignalR Service in the search box and press enter.

Select SignalR Service from the search results, then select Create.
Enter the following settings.
Setting Suggested value Description Resource name Globally unique name Name that identifies your new SignalR Service instance. Valid characters are a-z,0-9, and-.Subscription Your subscription The subscription under which this new SignalR Service instance is created. Resource Group myResourceGroup Name for the new resource group in which to create your SignalR Service instance. Location West US Choose a region near you. Pricing tier Free Try Azure SignalR Service for free. Unit count Not applicable Unit count specifies how many connections your SignalR Service instance can accept. It is only configurable in the Standard tier. Service mode Serverless For use with Azure Functions or REST API. 
Select Create to start deploying the SignalR Service instance.
After the instance is deployed, open it in the portal and locate its Settings page. Change the Service Mode setting to Serverless only if you are using Azure SignalR Service through Azure Functions binding or REST API. Leave it in Classic or Default otherwise.
Having issues? Try the troubleshooting guide or let us know.
Setup and run the Azure Function locally
Make sure you have Azure Function Core Tools installed. And create an empty directory and navigate to the directory with command line.
# Initialize a function project func init --worker-runtime pythonAfter you initialize a project, you need to create functions. In this sample, we need to create 3 functions.
Run the following command to create a
indexfunction, which will host a web page for client.func new -n index -t HttpTriggerOpen
index/function.jsonand copy the following json codes:{ "bindings": [ { "authLevel": "anonymous", "type": "httpTrigger", "direction": "in", "name": "req", "methods": [ "get", "post" ] }, { "type": "http", "direction": "out", "name": "res" } ] }Open
index/__init__.pyand copy the following codes.import os import azure.functions as func def main(req: func.HttpRequest) -> func.HttpResponse: f = open(os.path.dirname(os.path.realpath(__file__)) + '/../content/index.html') return func.HttpResponse(f.read(), mimetype='text/html')Create a
negotiatefunction for clients to get access token.func new -n negotiate -t SignalRNegotiateHTTPTriggerOpen
negotiate/function.jsonand copy the following json codes:{ "scriptFile": "__init__.py", "bindings": [ { "authLevel": "anonymous", "type": "httpTrigger", "direction": "in", "name": "req", "methods": [ "post" ] }, { "type": "http", "direction": "out", "name": "$return" }, { "type": "signalRConnectionInfo", "name": "connectionInfo", "hubName": "serverless", "connectionStringSetting": "AzureSignalRConnectionString", "direction": "in" } ] }And open the
negotiate/__init__.pyand copy the following codes:import azure.functions as func def main(req: func.HttpRequest, connectionInfo) -> func.HttpResponse: return func.HttpResponse(connectionInfo)Create a
broadcastfunction to broadcast messages to all clients. In the sample, we use time trigger to broadcast messages periodically.func new -n broadcast -t TimerTrigger # install requests pip install requestsOpen
broadcast/function.jsonand copy the following codes.{ "scriptFile": "__init__.py", "bindings": [ { "name": "myTimer", "type": "timerTrigger", "direction": "in", "schedule": "*/5 * * * * *" }, { "type": "signalR", "name": "signalRMessages", "hubName": "serverless", "connectionStringSetting": "AzureSignalRConnectionString", "direction": "out" } ] }Open
broadcast/__init__.pyand copy the following codes.import requests import json import azure.functions as func def main(myTimer: func.TimerRequest, signalRMessages: func.Out[str]) -> None: headers = {'User-Agent': 'serverless'} res = requests.get('https://api.github.com/repos/azure/azure-signalr', headers=headers) jres = res.json() signalRMessages.set(json.dumps({ 'target': 'newMessage', 'arguments': [ 'Current star count of https://github.com/Azure/azure-signalr is: ' + str(jres['stargazers_count']) ] }))
The client interface of this sample is a web page. Considered we read HTML content from
content/index.htmlinindexfunction, create a new fileindex.htmlincontentdirectory under your project root folder. And copy the following content.<html> <body> <h1>Azure SignalR Serverless Sample</h1> <div id="messages"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/3.1.7/signalr.min.js"></script> <script> let messages = document.querySelector('#messages'); const apiBaseUrl = window.location.origin; const connection = new signalR.HubConnectionBuilder() .withUrl(apiBaseUrl + '/api') .configureLogging(signalR.LogLevel.Information) .build(); connection.on('newMessage', (message) => { document.getElementById("messages").innerHTML = message; }); connection.start() .catch(console.error); </script> </body> </html>It's almost done now. The last step is to set a connection string of the SignalR Service to Azure Function settings.
In the browser where the Azure portal is opened, confirm the SignalR Service instance you deployed earlier was successfully created by searching for its name in the search box at the top of the portal. Select the instance to open it.

Select Keys to view the connection strings for the SignalR Service instance.

Copy the primary connection string. And execute the command below.
func settings add AzureSignalRConnectionString "<signalr-connection-string>"
Run the Azure Function in local:
func startAfter Azure Function running locally. Use your browser to visit
http://localhost:7071/api/indexand you can see the current star count. And if you star or unstar in the GitHub, you will get a star count refreshing every few seconds.Note
SignalR binding needs Azure Storage, but you can use local storage emulator when the Function is running locally. If you got some error like
There was an error performing a read operation on the Blob Storage Secret Repository. Please ensure the 'AzureWebJobsStorage' connection string is valid.You need to download and enable Storage Emulator
Clean up resources
If you're not going to continue to use this app, delete all resources created by this quickstart with the following steps so you don't incur any charges:
In the Azure portal, select Resource groups on the far left, and then select the resource group you created. Alternatively, you may use the search box to find the resource group by its name.
In the window that opens, select the resource group, and then click Delete resource group.
In the new window, type the name of the resource group to delete, and then click Delete.
Having issues? Try the troubleshooting guide or let us know.
Next steps
In this quickstart, you built and ran a real-time serverless application in local. Learn more how to use SignalR Service bindings for Azure Functions. Next, learn more about how to bi-directional communicating between clients and Azure Function with SignalR Service.