Integrating Naurt’s Geocoder with Swift

NOTE: As of right now, this will only work on MacOS and Linux machines. The server dependency, Vapor, is currently not supported on Microsoft Windows. Please see https://github.com/vapor/vapor/issues/2646 and https://github.com/apple/swift-nio/issues/2065. We’ll update this blog once Windows support comes, hopefully soon!

September 16, 2024

Setting Up the Environment

The set up will vary slightly depending on what platform you use. I will be setting this up on an ArchLinux machine for use with the command line. If you’re using a different platform, see the instructions here.

On ArchLinux, you can use yay to install Swift

yay -S swift-bin

Then initialise the Swift project with

swift package init --type executable

We’ll use Vapor as the web, server, so install it by making this the contents of your Package.swift file

// swift-tools-version: 5.10
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
    name: "NaurtExample",
    dependencies: [
        .package(url: "https://github.com/vapor/vapor.git", from: "4.0.0")
    ],
    targets: [
        // Targets are the basic building blocks of a package, defining a module or a test suite.
        // Targets can depend on other targets in this package and products from dependencies.
        .executableTarget(
            name: "NaurtExample",
            dependencies: [
                .product(name: "Vapor", package: "vapor")
            ]
            ),
    ]
)

And then fetch the dependencies with

swift package update

Setting Up a Basic Web Server

We’ll create a basic web server with Vapor. I deviate from the Vapor introductory docs slightly in the implementation - I don’t think the example there is as illuminating. I think the most scalable way to structure this is with three elements

  1. A main  function where top-level configuration can take place
  2. A function which let’s us associate endpoints with specific handler functions
  3. Handler functions themselves

So, the implementation we’ll use is the following

import Vapor

func main() throws {
    var env = try Environment.detect()
    let app = Application(env)
    defer { app.shutdown() }

    try configureRoutes(app)

    try app.run()
}

func configureRoutes(_ app: Application) throws {
    app.get(use: helloWorldHandler)
}

func helloWorldHandler(req: Request) -> Response {
    return Response(status: .ok, body: .init(string: "Thanks for calling me!"))
}

try main()

At this point you can run this with

swift build
swift run

And then go to http://localhost:8080 - if everything went well you should see a simple reply from the server.

A Free Naurt API Key

If you haven’t already, sign up at Naurt’s dashboard for a free key. The free key comes loaded with thousands of API requests per month, so there’s no cost to try it out. We don’t require a credit card for sign up, either!

For this post, I’ll be placing my API key in a file called api.key. Make sure the file is next to the Package.swift file. In most backend applications, this will probably be injected via an environment variable or a secret.

For us, just having this as a global variable will suffice, so we can place this at the top of the main.swift file

struct Config {
    static let apiKey: String = {
        let filePath = "api.key"
        do {
            let fileContents = try String(contentsOfFile: filePath, encoding: .utf8)
            return fileContents
        } catch {
            fatalError("API Key file not found")
        }
    }()
}

Just before the main function executes the API key will be stored in this struct.

Basic Naurt Request

Obviously our web server will be far more useful once we actually make requests to Naurt. Let’s replace our handler function with the following code

func handler(req: Request) async throws -> Response {
    let response = try await req.client.post("https://api.naurt.net/final-destination/v1") { req in

    try req.content.encode(["address_string": "The Grand Hotel, Brighton"])

    req.headers.add(name: "Authorization", value: Config.apiKey)
}

    guard response.status == .ok else {
        return Response(status: .internalServerError, body: .init(string: "Failed to fetch data from the external API"))
    }

    var headers = HTTPHeaders()
    headers.add(name: .contentType, value: "application/json")
    let jsonString = String(buffer: response.body!)

    return Response(status: .ok, headers: headers, body: .init(string: jsonString))

}

Just a few things to note here - we’ve hard coded in a request, but we’ll come back to that later. We use let jsonString = String(buffer: response.body!) to convert the bytes of the response into a utf8 string which we can actually send back to the user.

Handling Query Parameters

Hard coding in a request isn’t so useful, since we’d have to recompile the program every time we wanted a new request. Instead, we’ll use query parameters in the URL. Before we do that, we need to create a helper struct to handle the encoding into a JSON. However, there’s two things we need to take note of

  1. In Swift, variable names are supposed to be camel case, but the Naurt JSON is snake case. So, we’ll store them as camel case in the code and only convert to snake case when we encode to a JSON
  2. Some of the parameters are optional, and we shouldn’t encode them when they aren’t present

Therefore, make the following struct. We make it conform to Content so it can fit into the Vapor ecosystem.

struct NaurtRequest: Content {
    let addressString: String?
    let additionalMatches: Bool?
    let latitude: Float?
    let longitude: Float?

    func encode(to encoder: any Encoder) throws {
        var container = encoder.container(keyedBy: CustomCodingKeys.self)

        if let addressString = self.addressString {
            try container.encode(addressString, forKey: .addressString)
        }

        if let additionalMatches = self.additionalMatches {
            try container.encode(additionalMatches, forKey: .additionalMatches)
        }

        if let latitude = self.latitude {
            try container.encode(latitude, forKey: .latitude)
        }

        if let longitude = self.longitude {
            try container.encode(longitude, forKey: .longitude)
        }
    }

    enum CustomCodingKeys: String, CodingKey {
        case addressString = "address_string"
        case additionalMatches = "additional_matches"
        case latitude = "latitude"
        case longitude = "longitude"
    }
}

Once we have that, actually parsing the query parameters is really easy in Vapor, we just need to update the handler function like so

func handler(req: Request) async throws -> Response {

    let addressString = req.query[String.self, at: "address_string"]
    let additionalMatches = req.query[Bool.self, at: "additional_matches"]
    let latitude = req.query[Float.self, at: "latitude"]
    let longitude = req.query[Float.self, at: "longitude"]

    let response = try await req.client.post("https://api.naurt.net/final-destination/v1") { req in

    let naurtRequest = NaurtRequest(addressString: addressString, additionalMatches: additionalMatches, latitude: latitude, longitude: longitude)
    try req.content.encode(naurtRequest)
   
    req.headers.add(name: "Authorization", value: Config.apiKey)
}
// Rest of the function...

Now you can try going to http://localhost:8080/?address_string=The Grand Hotel, Brighton to see this working!

Visualising the GeoJSON

The majority of the data returned by Naurt is inside a GeoJSON. While this is a great format, it isn’t really designed for humans to read. The best way to visualise the GeoJSON is of course on a map. We’ll use a simple Leaflet script to do that, and we’ll insert the Naurt response using Lead - Vapor’s templating library. To install Leaf, update the Package.swift like so

// swift-tools-version: 5.10
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
    name: "NaurtExample",
    dependencies: [
        .package(url: "https://github.com/vapor/vapor.git", from: "4.0.0"),
        .package(url: "https://github.com/vapor/leaf.git", from: "4.0.0")
    ],
    targets: [
        // Targets are the basic building blocks of a package, defining a module or a test suite.
        // Targets can depend on other targets in this package and products from dependencies.
        .executableTarget(
            name: "NaurtExample",
            dependencies: [
                .product(name: "Vapor", package: "vapor"),
                .product(name: "Leaf", package: "leaf")
            ]
            ),
    ]
)

Don’t forget to update the packages with

swift package update

Create a folder next to Sources called Resources and then a Views folder inside that. Create a file called index.leaf . This will be our template, and the contents are

<!DOCTYPE html>
<html>

<head>
    <title>Naurt Geocoder</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
    <style>
        #map {
            height: 100vh;
        }
    </style>
</head>

<body>
    <div id="map"></div>
    <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
    <script>

        function getColor(type) {
            switch (type) {
                case 'naurt_door': return '#FF0000';
                case 'naurt_building': return '#9d79f2';
                case 'naurt_parking': return '#00FF00';
                default: return '#000000';
            }
        }

        function style(feature) {
            return {
                fillColor: getColor(feature.properties.naurt_type), weight: 2, opacity: 1, color: 'white', dashArray: '5', fillOpacity: 0.4
            };
        }

        function onEachFeatureCurry(address) {
            return function onEachFeature(feature, layer) {
                if (feature.properties) {
                    var popupContent = 'Type: ' + feature.properties.naurt_type;
                    if (feature.properties.naurt_type == 'naurt_building') {
                        popupContent += '<br>Address: ' + address;
                    }
                    layer.bindPopup(popupContent).openPopup();
                }
            }
        }



        var map = L.map('map').setView([0, 0], 2);
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19, attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' }).addTo(map);
        var response = #unsafeHTML(NaurtResponse);


        L.geoJSON(response["best_match"]["geojson"], { style: style, onEachFeature: onEachFeatureCurry(response["best_match"]["address"]) }).addTo(map);

        if ("additional_matches" in response) {
            for (const additionalMatch of response["additional_matches"]) {
                L.geoJSON(additionalMatch["geojson"], { style: style, onEachFeature: onEachFeatureCurry(additionalMatch["address"]) }).addTo(map);
            }
        }

        var bounds = L.geoJSON(response["best_match"]["geojson"]).getBounds();
        map.fitBounds(bounds);
    </script>
</body>


</html>

I won’t walk through every detail of the template, as it’s pretty self-explanatory. I’ll just note that the basic idea here is to plot each aspect of the GeoJSON - naurt_door, naurt_parking, naurt_building - as its own layer. We also check to see if there are additional_matches, and if there are, loop over them and plot them in the same way as the best_match.

To actually use the template we just need to do a few things.

First, import Leaf at the top of main.swift

import Leaf

Then add Leaf to the main function

func main() throws {

    var env = try Environment.detect()
    let app = Application(env)
    defer { app.shutdown() }

    app.views.use(.leaf)

    try configureRoutes(app)

    try app.run()
}

And then just update the end of handler

 	  // Rest of function...		 
    guard response.status == .ok else {
        return Response(status: .internalServerError, body: .init(string: "Failed to fetch data from the external API"))
    }

    let jsonString = String(buffer: response.body!)

    let context = ["NaurtResponse": jsonString]
    return try await req.view.render("index", context).encodeResponse(status: .ok, for: req)
}

This will render the template, and also encode it to a Response. Normally, with Leaf templates you return a EventLoopFuture<View>  however, we sometimes need to return different kinds of responses (when there’s an error), so that doesn’t work here.

And that’s it!

If you run the server again and go to http://localhost:8080/?address_string=The Grand Hotel, Brighton&additional_matches=true you should see the following

Subscribe To Our Newsletter - Sleek X Webflow Template

Subscribe to our newsletter

Sign up at Naurt for product updates, and stay in the loop!

Thanks for subscribing to our newsletter
Oops! Something went wrong while submitting the form.