Permalink

I made my first API today, and I used Swift to do it!

Basically, I got bored this afternoon and decided to have a little research into server-side Swift programming. I’ve heard about this before, but I’ve not gone too deep into it myself.

The problem with me tying things like this, is that I ever really have a good idea, or scenario which I could use to learn the new thing. Well as you may already know, I’m slowly working on a title casing application for iOS and macOS, and therefore I’ve already created a few functions to format text.

So far the base TextCase functions are:

  • Uppercase
  • Lowercase
  • Title Case
  • URL Encoding
  • Mocking SpongeBob (yes, like the meme)

From these formats, the only ones I could see being useful are Title casing, and the fun SpongeBob format.

From making use of various APIs myself, I knew that all I needed was a super simple HTTP server, which had support for a few GET requests.

Perfect was the tool I used to write the server side code, and I found a quick tutorial which explained the basic HTTP server that I needed. I must say it was really easy for me to create this, as I’m already familiar with Swift, so the only thing to learn was the “Perfect” way of doing things.

Because it was in Swift, I could also reuse my main TextCase class which handles the formatting. There was a slight exception, where the arc4random_uniform function isn’t available on Linux, but I found a Linux suitable replacement for this.

There are also a few more reasons why I wanted to try this out, but they’re rather meta. For example, I’m a big fan of Swift, and it feels good working with “low-level” Swift if you can really call it that, and also because I just love the look of Swift in the default Xcode theme, with the SF Mono font 😍 (weird, I know, but it’s the truth).

The final code (as in what I’ve done so far), is three endpoints, which are actually just two. /title/{input text} is to return the given text in title casing, /spongebob/{input text} is for the SpongeBob case. The third one is just /{input text}, and it returns the text in every format available, which is just the two I mentioned so far. The results are in plain JSON, and also include the plain value that was sent in the request.

For example, here is an example response to the / endpoint:

{
    "plain" : "what the hell is this",
    "title" : "What the Hell Is This",
    "spongebob" : "wHAT ThE Hell iS thiS"
}

Anyway, you can view the project over at GitHub, and if you want to suggest any new formats (or even write some yourself), just let me know on Twitter at @chrishannah