Build a Serverless API with Azure Functions
Create a Function App
Go to Azure Portal > Create a Resource > Compute > Function App
Basic Setup:
- Runtime stack: Python
- Region: Closest to your users
- Hosting plan: Consumption (pay-per-use)
Choose the Trigger Type: HTTP
Once the Function App is ready, go to Functions > Add
Choose HTTP trigger
Give it a name (e.g., GetUsers) and choose Authorization level: Function (or Anonymous for testing)
Write the API Code
import azure.functions as func
import json
def main(req: func.HttpRequest) -> func.HttpResponse:
name = req.params.get('name')
if not name:
try:
req_body = req.get_json()
except ValueError:
pass
else:
name = req_body.get('name')
if name:
return func.HttpResponse(f"Hello, {name}!")
else:
return func.HttpResponse("Please pass a name on the query string or in the request body", status_code=400)
Output:
GET https://
Returns: Hello, Azure!
Test Your API
You can test with:
curl "https://.azurewebsites.net/api/GetUsers?name=Azure"
Or use Postman for a POST request with a JSON body.
Add More Routes
Add more function files, like:
- GetUserById
- AddUser
- DeleteUser
- UpdateUser
You now have a mini-REST API!
Persist Data
Bind Azure Functions to storage:
- Cosmos DB: Add a user, retrieve by ID
- Blob Storage: Upload or download files
- Table Storage: Lightweight key-value storage
Example: Add Cosmos DB binding in function.json
{
"bindings": [
{
"type": "cosmosDB",
"name": "outputDocument",
"databaseName": "UsersDB",
"collectionName": "Users",
"createIfNotExists": true,
"connectionStringSetting": "CosmosDBConnection",
"direction": "out"
}
]
}
Secure Your API
Use function keys or Azure AD
Add rate limits and IP restrictions in Function App settings
Monitor and Scale
Azure Functions scale automatically under load
Use Application Insights for logs, errors, and performance
View metrics under “Monitoring” in the Function App blade