zoukankan      html  css  js  c++  java
  • RESTful API 设计

    网络应用程序,分为前端和后端两个部分。当前的发展趋势,就是前端设备层出不穷(手机、平板、桌面电脑、其他专用设备......)。

    因此,必须有一种统一的机制,方便不同的前端设备与后端进行通信。这导致API构架的流行。

    RESTful API 设计要素详见此文 : RESTful API 设计指南

    以下简诉API的测试和它在PHP中的异常处理:

    安装浏览器扩展工具 Restlet Client - DHC ,用于API的调试/测试

     

    异常处理:

        /**
         * 常用状态码
         * @var [type]
         */
        private $_statusCodes = array(
            200 => 'OK',
            204 => 'No Content',
            400 => 'Bad Request',
            401 => 'Unauthorized',
            403 => 'Forbidden',
            404 => 'Not Found',
            405 => 'Method Not Allowed',
            500 => 'Server INternal Error'
        );
        /**
         * 判断请求方法和资源对象
         * @return [type] [description]
         */
        public function run()
        {
            //异常捕获,以免被暴露在前台
            try {
                $this->_setupRequestMethod();
                $this->_setupResource();
                if ($this->_resourceName == 'users') {
                    return $this->_json($this->_handleuser());
                } else {
                    return $this->_json($this->_handleArticle());
                }
            } catch (Exception $e) {
                $arr['error'] = $e->getMessage(); 
                $this->_json($arr, $e->getCode());
            }
        }
        /**
         * 输出JSON
         * @param  [type] $array [description]
         * @return [type]        [description]
         */
        private function _json($array, $code = 0)
        {
            //同步响应码
            if ($code > 0 && $code !== 200 && $code !== 204) {
                header("HTTP/1.1 " . $code . " " . $this->_statusCodes[$code]);
            }
            
            header('Content-Type:application/json;charset=utf-8');
            // echo json_encode($array, JSON_UNESCAPED_UNICODE);
            echo json_encode($array);
            exit();
        }
        /**
         * 获取请求参数
         * @return [type] [description]
         */
        private function _getBodyParams()
        {
            //所传参数用双引号
            $raw = file_get_contents('php://input');
            if (empty($raw)) {
                throw new Exception('请求参数错误', 400);
            }
            return json_decode($raw, true);
        }
  • 相关阅读:
    [cf1038E][欧拉路]
    [最小费用最大流(板子)]
    [网络流24题]
    [ACM International Collegiate Programming Contest, Amman Collegiate Programming Contest (2018)]
    [Split The Tree][dfs序+树状数组求区间数的种数]
    [CSL 的魔法][求排序最少交换次数]
    [CSL 的字符串][栈,模拟]
    ZOJ 3949 Edge to the Root 树形DP
    第十三周 Leetcode 363. Max Sum of Rectangle No Larger Than K(HARD)
    POJ 2104 HDU 2665 主席树 解决区间第K大
  • 原文地址:https://www.cnblogs.com/lishalom/p/6617168.html
Copyright © 2011-2022 走看看