晴明的博客园 GitHub      CodePen      CodeWars     

[http] RESTful API(2)

function resource(key) {
        if (typeof ctx.params.id !== 'undefined') {
            if(Array.isArray(ctx.body)){
                if(ctx.body.length > 0){
                    ctx.body = ctx.body[0];
                }else{
                    ctx.body = {
                        [key]: []
                    }
                }
            }else{
                ctx.body = {
                    [key]: ctx.body 
                }
            }
        } else {
            ctx.body = {
                [key]: ctx.body
            }
        }
}

URI规范

不要用大写

单词间使用下划线_

white/building (bad) 
	
white_building (good)

不使用动词,资源要使用名词形式,如:user、room、ticket
操作所有资源时用名词复数形式

层级 >= 三层,则使用'?'带参数

user/address/city/nanjing (bad) 
	
user/address/?city=nanjing (good)

Request Method

GET:查询资源
POST:创建资源
PUT:更新资源
DELETE:删除资源

参数

GET

非id的参数使用'?'方式传输

/users/1?state=closed

POST、PUT、DELETE

非id的参数使用body传输

过滤

?type=1&state=closed

分页

?limit=10&offset=10

limit:返回记录数量
offset:返回记录的开始位置

版本控制

/v1/api

Http Code



200	Request OK
	ctx.status = 200;
	ctx.body = data;

201	Resource created

204 No Content
	ctx.status = 204;
	ctx.body = {};

304 Not Modified
	
400	Validation error
	ctx.status = 400;
	ctx.body = {
		name: 'Validation error',
		message: 'Invalid request message framing, malformed request syntax,or deceptive request routing.',
		detail: 'invalid request'
	};

401	Unauthorized request
	ctx.status = 401;
	ctx.body = {
		name: 'Unauthorized error',
		message: 'Authentication is required but has failed or has not yet been provided.',
		detail: 'you may need to log in'
	};

402	Failed request
	ctx.status = 402;
	ctx.body = {
		name: 'Storage error',
		message: 'Client or server's storage was not stored properly.'
	};

403	Forbidden
	ctx.status = 403;
	ctx.body = {
		name: 'Forbidden error',
		message: 'The request was a valid request, but the server is refusing to respond to it.',
		detail: '5 text messages can be sent within one day by 1 person'
	};

404	Resource was not found

500 Internal Server Error
	ctx.status = 500;
	ctx.body = {
		name: 'Server error',
		message: 'An unexpected condition was encountered in the server and no more specific message is suitable.'
	};

502 Bad Gateway

503 Service Unavailable

504 Gateway Time-out

posted @ 2016-12-02 11:30  晴明桑  阅读(209)  评论(0编辑  收藏  举报