Writing & Publishing Azure Functions in Swift (Custom Handler Edition)
A couple of months ago, I wrote an article to take your through writing your first Azure Function in Swift, after releasing the Azure Function Swift worker. Now that Azure Functions added another way of supporting custom runtimes, the custom handlers, which support an HTTP worker.
I’ve worked on updating the framework to support Custom Handlers as well, with the same easy and convenient development experience the Swift Functions CLI tools bring.
Checklist
If you already write iOS apps, work with Swift, or Server Side Swift then you’re almost ready!
- Swift 5.2 or later/Xcode 11 or later on macOS. Swift installation
- Azure Functions Core Tools
- Swift Functions tools, from Homebrew 🍺, if you’re installing on macOS:
brew install salehalbuga/formulae/swift-func
If you already have it installed, make sure to update to the latest version.
brew upgrade swift-func
On Linux:
Clone the repo the tools repo
git clone https://github.com/SalehAlbuga/azure-functions-swift-tools
Then install:
make install
Creating the project
Using swiftfunc is very easy if you’re familiar with Azure Functions Core Tools.
- init: create a new project
- new: create a new function from a template
In a terminal run the following to create a new project:
swiftfunc init myFunctionApp -hw
Note the option -hw or — http-worker to specify that the new project will be created as a Custom Handler project
Your new project has the following folder structure:
The project is basically a SwiftPM project with the Swift Azure Functions framework dependency and a couple of extra files for the purpose of it.
cd
into the new folder and run:
swiftfunc new http -n helloWorld -hw
Now you have created a new HTTP triggered function!
Open the project in XCode (by opening Package.swift) and take a look at the code
import Foundation
import AzureFunctions
import Vaporclass helloWorld: Function {required init() {
super.init()
self.name = "helloWorld"
self.functionJsonBindings =
[
["authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [ "get", "post"]],
["type": "http",
"direction": "out",
"name": "res"]
]
// or
// self.trigger = HttpRequest(name: "req", methods: ["GET", "POST"]) app.get([PathComponent(stringLiteral: name)], use: run(req:))
app.post([PathComponent(stringLiteral: name)], use: run(req:))}func run(req: Request) -> String {
if let name: String = req.query["name"] {
return "Hello, \(name)!"
} else if let name: String = req.content["name"] {
return "Hello, \(name)!"
} else {
return "Hello!"
}
}}
This framework uses the famous Vapor web framework and makes Azure Functions development in Swift very easy and convenient!
As you can see in the function class initializer, you can set the trigger/bindings in JSON (Dictionary) format in functionJsonBindings property, just like you’d do manually when you create a function.json or you can use the framework’s predefined binding types by setting the other properties (trigger, inputBindings, and outputBindings)
Running the Function locally
To run the project:
swiftfunc run
Swift Functions Tools will compile the code, export the project and start the Azure Functions Host for you (as if you were running func host start
)
Click on the link from the Host output to navigate to your function!
http://localhost:7071/api/helloWorld
Pass a name param in query string or send a POST request with a name param in the body!
Congrats! You created your first Azure Function app in Swift. Let’s deploy that!
Deploying to Azure ☁️
The framework provides you with all you need to deploy. The provided Dockerfile is ready to go! Build the image
docker build -t <dockerHubNameOrRegistryUrl>/myswiftfunctions:v1 .
Push it to an image registry of your choice (DockerHub or Azure Container Registry)
docker push <dockerHubNameOrRegistryUrl>/myswiftfunctions:v1
You can deploy a prebuilt sample to your Azure account here or the link below, if you don’t have Docker installed.
Create a new Function App on Azure
Now that you have built your image, open Azure Portal if you have a subscription or Get one for free
- Click Create a resource
- Search for Function App
- Fill the basic required info, Resource Group, App Name and make sure to choose Docker Container for Publish
- Choose a region a hosting option. For more info about hosting options https://docs.microsoft.com/en-us/azure/azure-functions/functions-scale You can go with Premium EP1 or a an App Service Plan of your choice.
- Click on Review + create and create the app once the validation is done.
- Once the app is created, open it and configure Container Settings
- Choose your image source and enter the name and tag and click Save
- Once the Function App finishes pulling and starting the container (you can check the status from the logs in the blade in the screenshot above). You can see your function in the Functions blade
- Click on it and navigate to Code + Test blade. From the dropdown list you can see the files of your function, function.json and helloWorld.swift. Click on Get function URL, copy it and navigate to it in a new tab!
You’ve just created & published your first Azure Function in Swift!
Amazing! You’ve made it this far! 💪 If you like the project, give it a 🌟 on GitHub. This project is being actively maintained and updated. For any issues or bug reports, please feel free to file an issue on GitHub. Don’t forget to check the docs Here📚 and join the Azure Functions Discord server!