1. 程式人生 > >網站搭建筆記精簡版---廖雪峰WebApp實戰-Day9:編寫API筆記

網站搭建筆記精簡版---廖雪峰WebApp實戰-Day9:編寫API筆記

什麼是web API?

如果一個URL返回的不是HTML,而是機器能直接解析的資料,這個URL就可以看成是一個Web API。

編寫API有什麼好處呢?

由於API就是把Web App的功能全部封裝了,所以,通過API操作資料,可以極大地把前端和後端的程式碼隔離,使得後端程式碼易於測試,前端程式碼編寫更簡單。

API函式

一個api也是一個網頁處理函式,因此將下列程式碼加到handlers.py檔案中。

@get('/api/users') # 當遇到字尾名為/aip/users的網頁時,執行以下程式碼
def api_get_users(*, page='1'):
    page_index = get_page_index(page)
    num = await User.findNumber('count(id)')
    p = Page(num, page_index)
    # 要是沒有user的話,返回空
    if num == 0:
        return dict(page=p, users=())
    users = await User.findAll(orderBy='created_at desc', limit=(p.offset, p.limit))
    # 有user的話,返回所有資訊,並將密碼覆蓋為'******'
    for u in users:
        u.passwd = '******'
    return dict(page=p, users=users)

上述函式返回的為dict,之後的response該middleware可將結果轉化為json檔案並返回。

API Error函式

當api呼叫錯誤的時候,系統會預設返回一個數字,這樣不友好,因此提出需要將返回值設定為字串,將其放入檔案apis.py中。內容如下。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = 'Michael Liao'

'''
JSON API definition.
'''

import json, logging, inspect, functools
# 基礎錯誤
class APIError(Exception):
    '''
    the base APIError which contains error(required), data(optional) and message(optional).
    '''
    def __init__(self, error, data='', message=''):
        super(APIError, self).__init__(message)
        self.error = error
        self.data = data
        self.message = message
# 輸入值無效
class APIValueError(APIError):
    '''
    Indicate the input value has error or invalid. The data specifies the error field of input form.
    '''
    def __init__(self, field, message=''):
        super(APIValueError, self).__init__('value:invalid', field, message)
# 資源未發現,資料庫裡沒有這個東西
class APIResourceNotFoundError(APIError):
    '''
    Indicate the resource was not found. The data specifies the resource name.
    '''
    def __init__(self, field, message=''):
        super(APIResourceNotFoundError, self).__init__('value:notfound', field, message)
# 沒有許可權
class APIPermissionError(APIError):
    '''
    Indicate the api has no permission.
    '''
    def __init__(self, message=''):
        super(APIPermissionError, self).__init__('permission:forbidden', 'permission', message)

最後在瀏覽器輸入http://localhost:9000/api/users即可完成awesome資料庫中user表查詢。

參考部落格
廖雪峰的官方網站
原始碼