Nim 言語で RESTful API 作ってみた

インストール

Mac なので、さくっと Homebrew でインストールします

$ brew install nim

インストールが完了したので、バージョンを確認します

$ nim -v
Nim Compiler Version 0.17.2 (2017-09-08) [MacOSX: amd64]
Copyright (c) 2006-2017 by Andreas Rumpf

active boot switches: -d:release -d:useLinenoise

サンプルアプリケーション作成

まずはサンプルアプリケーションを配置するディレクトリを作成し、そのディレクトリに移動してから nimble init コマンドで nimble ファイルを新規作成します

$ mkdir sample_nim
$ cd sample_nim
$ nimble init sample_app
      Info: In order to initialise a new Nimble package, I will need to ask you
        ... some questions. Default values are shown in square brackets, press
        ... enter to use them.
    Prompt: Initial version of package? [0.1.0]
    Answer:
    Prompt: Your name? [enomotodev]
    Answer:
    Prompt: Package description?
    Answer: Sample Application
    Prompt: Package license? [MIT]
    Answer:
    Prompt: Lowest supported Nim version? [0.17.2]
    Answer:
   Success: Nimble file created successfully

Package description? の項目は必須項目のようだったので、Sample Application と回答し、他は空欄のままにしました

nimble とは nim でのパッケージ管理ツールで、Ruby でいう gem や、Node.js でいう npm みたいなもののようです

ルーティングとレスポンス用に jester というパッケージをインストールしてみたいと思います

$ nimble install jester
    Prompt: No local packages.json found, download it from internet? [y/N]
    Answer: y
Downloading Official package list
    Success Package list downloaded.
Downloading https://github.com/dom96/jester using git
  Verifying dependencies for jester@0.2.0
 Installing jester@0.2.0
   Success: jester installed successfully.

インストールできたので、早速コードを書いていきたいと思います

  • sample_app.nim
import jester, asyncdispatch, json

routes:
  get "/":
    resp "Hello World!"

runForever()

/ にアクセスされたら Hello World! を返すだけの簡単なコードですが、実際に実行してブラウザで確認してみたいと思います

$ nim c -r sample_app.nim
...(略)
INFO Jester is making jokes at http://localhost:5000

f:id:enomotodev:20171007130641p:plain

ブラウザでも確認できました!

次に /users/ID のような形の URL の時に、その ID を json 形式で返すようにしてみたいと思います

import jester, asyncdispatch, json

routes:
  get "/":
    resp "Hello World!"
  get "/users/@id":
    var data = %*{"id": @"id"}
    resp $data, "application/json"

runForever()

%* でハッシュを json 型にキャストし、$json 型を string にキャストしています

resp の第二引数では Response headers の content-type を指定しています

こちらもブラウザで確認してみましょう!

f:id:enomotodev:20171007130714p:plain

まとめ

まだまだパッケージは少ない印象ですが、比較的簡単に API 機能が実装できました

今回はデータベースと連携していないので、次は MySQL と連携して、ユーザ情報を返すようにしていきたいと思います

次の記事

enomotodev.hatenablog.com

enomotodev.hatenablog.com

Nim in Action

Nim in Action