LoginSignup
2

More than 1 year has passed since last update.

SwiftのサーバーサイドフレームワークVaporでのルーティング

これは何?

SwiftのサーバーサイドフレームワークVaporのAPIのルーティング方法をまとめたものです。

ルーティングをどこに記述をするのか

Vapor のプロジェクトを作成すると App 直下に routes.swift ファイルが自動で生成されているため、
ルーティングの設定はこちらに追記していく形になります。

書き方

ざっくり2種類の書き方があります。

func routes(_ app: Application) throws {
    app.get("foo") { req in
        return "foo"
    }
    app.on(.GET, "bar") { req in
        return "bar"
    }
}

app.xxx 形式では以下のメソッドが用意されています

  • get
  • post
  • patch
  • put
  • delete

その他のHTTP Methodを使いたい場合は on を使う必要があります

app.on(.OPTIONS, "options") { req in
}
app.on(.HEAD, "head") { req in
}

ネストしたURLの扱い

2種類の書き方があるので用途に合わせて使い分けて下さい


let hello = app.grouped("hello")
// GET /hello
hello.get { req in
}
// GET /hello/:name
hello.get(":name") { req in
    let name = req.parameters.get("name")!
}
app.group("hello") { hello in
    // GET /hello
    hello.get { req in
    }
    // GET /hello/:name
    hello.get(":name") { req in
        let name = req.parameters.get("name")!
    }
}

パラメータの渡し方

URL

URLのパスパラメータは :xxx 形式で渡すことができます

app.get("hello", ":name") { req -> String in
    let name = req.parameters.get("name")!
    return "Hello, \(name)!" // URL: /hello/example -> print: Hello, example!
}

クエリーパラメータの場合は以下のように渡すことができます

app.get("hello") { req -> String in
    let name = req.query["name"]!
    return "Hello, \(name)!"  // URL: /hello?name=example -> print: Hello, example!
}

リクエストボディ

Vaporが用意した protocol の Content を使い中身を取得することができます

struct PostContent: Content {
    var name: String
}

app.post("hello") { req -> String in
    let content = try req.content.decode(PostContent.self)
    return "Hello, \(content.name)!"
}
curl -X POST -H "Content-Type: application/json" -d '{"name":"world"}' localhost:8080/hello

終わりに

Vaporのルーティング方法をまとめました
普段iOS開発でSwiftに馴染みのある人だったら理解しやすいと思うので、この記事で興味を持ったら使ってみてると良いと思います

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
2