于志腾的技术专栏 PHP and Python and Vue Coder

如何设计restful api

2017-06-06
YztSon

阅读:

php

六要素

  1. 资源路径uri
  2. http 动词
  3. 过滤信息(其实就是信息处理,分页数据量)
  4. 状态码(200/204删除/400缺少参数/401没有权限或者没有登陆)
  5. 错误处理(错误码 ➕ 语述)
  6. 返回结果(json)

关于php的http基本认证

  1. 当某个页面需要认证才能进行访问时,接到请求后服务器端会在响应头中发送一个 WWW-Authenticate 首部(用来标识认证安全域),语法为WWW-Authenticate:Basic relam=quoted-string
  2. 默认格式: 当用户输入用户名和密码并且点击确定后,请求头会发送一个 Authorization 首部, 语法为 Authorization:Basic Base64(username:password)
  3. Authorization 可以自定义,传送Date

认证

一般认证

/**
	 * 要求认证
	 * @return bool|array
	 * @throws MyHttpException
	 */
	private function requestAuth()
	{
		if (!empty($_SERVER['PHP_AUTH_USER']) && !empty($_SERVER['PHP_AUTH_PW']))
		{
			try
			{
				$user = $this->user->login($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
				return $user;
			}
			catch (MyHttpException $e)
			{
				if ($e->getStatusCode() != 422)
				{
					throw $e;
				}
			}
		}
		header("WWW-Authenticate:Basic realm='Private'");
		header('HTTP/1.0 401 Unauthorized');
		print "You are unauthorized to enter this area.";
		exit(0);
	}

自定义认证

//自定义常量
$token = md5($str . $this->signDate);

        if (strcmp($token, $this->signToken) !== 0) {
            throw new ApiException(ApiException::SIGNATURE_ERROR_MESSAGE, ApiException::INVALID_SIGNTOKEN);
        }

获取用户资源

  1. 获取请求参数
$raw = file_get_contents('php://input');
$res = json_decode($raw, true)


下一篇 python之set运用

Comments

Content