« Muxtape を使ってみた
» [Edge Rails] DBコンソールを楽に起動:DB Console

Rails

RESTfulなRailsをtelnetで試す

2008/05/15

いまさらですが必要になったので、Rails2.0 の scaffold で、RESTfulなアプリを試してみました。確認に手間取ったのでメモ。

RESTfulなアプリを作成

いつもどおり scaffold で、アプリを作成します。

1
2
3
4
5
$ rails rest
$ cd test
$ script/generate scaffold entry title:string description:text
$ rake db:migrate
$ script/server -p 3333

3行目では、titleとdescriptionを持ったentryモデルを作成しています。

確認

GET(データ取得)、DELETE(データ削除)は試せたのですが、POST(データ追加)とPUT(データ更新)がいまいち試せてなかったので、telnetで試してみました。

1
2
3
4
5
6
7
8
9
$ telnet localhost 3333
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
POST /entries.xml HTTP/1.1
Content-Type: application/xml
Content-Length: 83
 
<entry><title>this is the title</title><description>desc desc</description></entry>

5行目よりHTTPメソッドを発行していて、6行目ではContent-Typeをxmlとしています(Content-Typeは必須のようですね)。7行目のContent-Lengthは、9行目に送信しているデータ(XML)のバイト数です。

この結果、下記のようなレスポンスが返ってきます。16,18行目では、指定したtitle, descriptionが入力されているのを確認することができます(もちろん、http://localhost:3333/entries/2 でも確認できます)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
HTTP/1.1 201 Created
Connection: close
Date: Wed, 14 May 2008 14:25:22 GMT
Set-Cookie:<>
Status: 201 Created
Location: http://:/entries/2
X-Runtime: 0.03339
Cache-Control: no-cache
Server: Mongrel 1.1.4
Content-Type: application/xml; charset=utf-8
Content-Length: 286
 
<?xml version="1.0" encoding="UTF-8"?>
<entry>
  <created-at type="datetime">2008-05-14T14:25:22Z</created-at>
  <description>desc desc</description>
  <id type="integer">2</id>
  <title>this is the title</title>
  <updated-at type="datetime">2008-05-14T14:25:22Z</updated-at>
</entry>

ちなみにわざわざtelnetを使わなくても、Firefoxのプラグインである Poster を使うとGUIでHTTPメソッドを発行できるので便利です。

Tags: , ,

have your say

Add your comment below, or trackback from your own site. Subscribe to these comments.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

:

:


« Muxtape を使ってみた
» [Edge Rails] DBコンソールを楽に起動:DB Console