分类
日记

用slim写的一个RESTful服务

php写rest服务,以下是一些资料和一个例子。仅供学习。

REST 资料:http://www.sitepoint.com/rest-can-you-do-more-than-spell-it-1/

SLIM资料:http://www.slimframework.com/(官网)

http://minimee.org/php/slim(中文文档)

https://github.com/codeguy/Slim-Extras/tree/master/Middleware(Slim的一些插件开源地址)

SLIM示例:http://www.sitepoint.com/writing-a-restful-web-service-with-slim/

同时推荐一个PHP数据库ORM类:http://www.notorm.com/

下面是我的例子:

  • GET /books: Retrieve a list of items
  • GET /book/123: Retrieve item 123
  • POST /book: Create a new item
  • PUT /book/123: Update item 123
  • DELETE /book/123: Remove item 123
<?php

//导入类库
require 'Slim/Slim.php';

//注册Slim框架自带的自动加载类
\Slim\Slim::registerAutoloader();

$dsn = "mysql:dbname=test;host=localhost";
$username = "root";
$password = "";

require "NotORM.php";
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//设置编码
$pdo->query('SET NAMES utf8');
$db = new NotORM($pdo);


//创建实例
$app = new \Slim\Slim(array(
    "MODE" => "development",
    "TEMPLATES.PATH" => "./templates"
));

$app->get("/", function() {
    echo "<h1>Hello Slim World</h1>";
});

$app->get("/books", function () use ($app, $db) {
    $books = array();
    foreach ($db->books()->limit(5) as $book) {
        $books[]  = array(
            "id" => $book["id"],
            "title" => $book["title"],
            "author" => $book["author"],
            "summary" => $book["summary"]
        );
    }
    $app->response()->header("Content-Type", "application/json");
    echo json_encode($books);
});


$app->get("/book/:id", function ($id) use ($app, $db) {
    $app->response()->header("Content-Type", "application/json");
    $book = $db->books()->where("id", $id);
    if ($data = $book->fetch()) {
        echo json_encode(array(
            "id" => $data["id"],
            "title" => $data["title"],
            "author" => $data["author"],
            "summary" => $data["summary"]
            ));
    }
    else{
        echo json_encode(array(
            "status" => false,
            "message" => "Book ID $id does not exist"
            ));
    }
});

$app->post("/book", function () use($app, $db) {
    $app->response()->header("Content-Type", "application/json");
     $input =$app->request()->getBody();
	 $input = json_decode($input); 
	 //取值
	 $book["title"]=$input->title  ;
	 $book["author"]=$input->author  ;
	 $book["summary"]=$input->summary  ;
	 //存储数据库
    $result = $db->books->insert($book);
    echo json_encode(array("id" => $result["id"]));
});


$app->put("/book/:id", function ($id) use ($app, $db) {
    $app->response()->header("Content-Type", "application/json");
    $book = $db->books()->where("id", $id);
    if ($book->fetch()) {
        //$post = $app->request()->getBody();
		//$post["author"]="test";
		//获取put包
		$input =$app->request()->getBody();
		//转换json对象
	    $input = json_decode($input); 
		//赋值
		$post["title"]=$input->title  ;
	    $post["author"]=$input->author  ;
	    $post["summary"]=$input->summary  ;
		$post["id"]=$id  ;
	    
        $result = $book->update($post);
        echo json_encode(array(
            "status" => (bool)$result,
            "message" => "Book updated successfully"
            ));
    }
    else{
        echo json_encode(array(
            "status" => false,
            "message" => "Book id $id does not exist"
        ));
    }
});

$app->delete("/book/:id", function ($id) use($app, $db) {
    $app->response()->header("Content-Type", "application/json");
    $book = $db->books()->where("id", $id);
    if ($book->fetch()) {
        $result = $book->delete();
        echo json_encode(array(
            "status" => true,
            "message" => "Book deleted successfully"
        ));
    }
    else{
        echo json_encode(array(
            "status" => false,
            "message" => "Book id $id does not exist"
        ));
    }
});

$app->run();

 

分类
学习笔记

Rest服务禁用WebDAV

在IIS7.0中,使用了WebDAV。

rest服务创建在虚拟目录中,调用中服务无法进行delete、put等操作,只有post和Get请求访问正常。禁用WebDaV访问正常。可见不允许的谓词put等由于WebDAV引起。

rest服务config文件中,按照以下配置,可让rest服务不启用webDav服务运行。

<system.webServer>
    <modules runAllManagedModulesForAllRequests="true" runManagedModulesForWebDavRequests="true" >
      <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
       <remove name="WebDAVModule" />
    </modules>
        <handlers>
            <remove name="WebDAV" />
        </handlers>
  </system.webServer>
分类
学习笔记

WCF REST service 400 Bad Request

WCF REST service 返回是400 错误。

默认超过65K传输时产生异常。解决Webcofig中webHttpEndpoint配置maxReceivedMessageSize 等。

<!-- 
            Configure the WCF REST service base address via the global.asax.cs file and the default endpoint 
            via the attributes on the <standardEndpoint> element below
        -->
        <standardEndpoint name="" maxBufferSize="2147483647"  maxReceivedMessageSize="2147483647" maxBufferPoolSize="0" helpEnabled="true" automaticFormatSelectionEnabled="true" faultExceptionEnabled="true">
          <readerQuotas maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647"  maxDepth ="2147483647" />
        </standardEndpoint>

以上放置在webHttpEndpoint节点下。

VS2010中有配置编辑器,可以用来编辑WCF中的webconfig

参考文章:

http://stackoverflow.com/questions/6599355/wcf-rest-service-400-bad-request

http://msdn.microsoft.com/zh-cn/ff657121

分类
学习笔记

WCF:REST服务接收http post数据的处理方法

通过定义UriTemplate,WebInvoke等就可以处理。

如下:

stream 输入流 例如:

[WebInvoke(UriTemplate = "import?url={encodedServiceUrl}", Method = "POST", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
        public ImportRest Create(Stream pstream, string encodedServiceUrl)

UriTemplate定义了参数匹配关系:我的参数如encodedServiceUrl,类型必须string

获取POST过来的数据信息。

定义Stream pstream参数就可以了。

获取代码如下:

 //获取requestBody
            string postJson = string.Empty;
            using (var reader = OperationContext.Current.RequestContext.RequestMessage.GetReaderAtBodyContents())
            {
                if (reader.Read())
                {
                   postJson = new string(Encoding.UTF8.GetChars(reader.ReadContentAsBase64()));
                }
            }

同样可以获取httpheader噢,如下:

 //获取requestHeard
            WebHeaderCollection headerCollection = WebOperationContext.Current.IncomingRequest.Headers;
            foreach (string item in headerCollection)
            {
                string value = headerCollection.Get(item);
            }