MOPCON
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Help
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    1
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # 優雅的 API 設計 - 後端工程師必修的設計模式 - 官承翰 {%hackmd rG6pzIawQKe5cHU4rycgYg %} :::success :::spoiler TableOfContent [TOC] ::: ## 講者: > 姓名:官承翰 > title:資深專家工程師 > [以前資料](https://hackmd.io/@mopcon/2019/%2F%40mopcon%2Frk0Vt8gYS) ~~抽不到 SSR~~ (~~是不是對不起優依~~) ~~阿貝神教錯了嗎~~ 原本以為不會通過審核 ![](https://i.imgur.com/QBMwXMS.png =200x) ## 前言 http (?) 科技大廠 帶著輕鬆愉快的心情 ## 大綱 ### HTTP IETF1986 TCP/IP溝通 ### REST- Representational State Transfer ### 科技大廠怎麼寫Restful的? Google / Facebook / Microsoft ## 成為一個懂 REST 的後端的理由 為什麼要熟悉這些東西? 前端工程師抱怨 API 寫太爛接不起來? ## HTTP Introduction - 網際網路工程任務組(IETF) - 1986年創立 - 一個國際化標準組織 - 主要負責所有TCP/IP的定義以及規範 - 全球網路資訊協會W3C - 1994年創立 - 一個國際化標準組織 - 主要負責解決網際網路平台兼容問題 瀏覽器實作跨平台問題 網路規格 - HTTP 是一種通訊協定 (不是一種明文的規範) - GET - HEAD - POST - PATCH - PUT - DELETE - OPTIONS - PATCH 單獨被定義在RFC5789 ## 先介紹狀態 - RFC2616 以及 RFC7231 - 1xx - 通常包含一些可用訊息 - HTTP/1.0 不行包涵1XX狀態 - 2xx - 表示伺服器成功 - 3xx - 被重新導向 - 4xx - 用戶端錯誤 - 5XX - 伺服器錯誤 ## 幾個常見被搞混的狀態 ### 200 vs 202 - 200 - 已經執行完畢 - 202 (Accepted) - 已經加入到 Queue 裡面等待被執行,未來的某一個時間點會被執行 ### 403 vs 401(也曾被講者搞錯!) - 403 (Forbidden) 沒有權限存取 - 使用者**已經登入**,但因為沒有權限無法查看 - 401 (Unauthorized) 沒有經過授權 - user**尚未登入**,無法查看指定頁面 ### 404 VS #410 - 404 (Not Found) 請求的資源或是網址不存在 - 這個網址**不曾**存在 - 這個資源不存在 - https://developers.google.com/drive/api/v3/handle-errors - 410 (Gone) 請求的資源曾經存在(現在不存在) - 電子商務中的產品暫時性下架等 ## 幾個常用的方式(無特殊功能的條件下) GET/POST/PUT/PATCH/OPTION/HEAD ### POST - 拿來建立資料使用 - 通常會回 status code(狀態碼) - 201 (Created) - 202 (Accepted) - 204 (No Content) - 參數在body - POST 很特別的是在 RFC7231 內定義為 **cacheable**,但是實際上沒有框架實作 ### GET - 拿來取得資料使用 - 通常會回 status code - 200 (OK) - 參數會在 query string ### PUT - 拿來更新或是新建資料使用 - 必須帶入「完整」的資料內容 - 通常會回 stauts code - 200 (OK) - 202 (Accepted) - 204 (No Content) - 路徑要有resource id - 參數會在body ### PATCH - 拿來**更新資料**使用 - 通常帶入「部分」的資料內容 - 通常會回 stauts code - 200 (OK) - 202 (Accepted) - 204 (No Content) - 路徑要有resource id - 參數會在body ### DELETE - 拿來「刪除資料」 - 通常帶入「部分」的資料內容 - 通常會回 stauts code - 200 (OK) - 202 (Accepted) - 204 (No Content) - 路徑要有resource id - 根據 W3C 的 RFC2616,**沒有特別鼓勵**透過 body來刪除資料,但通常框架都不理會。 ### OPTIONS - 拿來跨網域請求的時候使用 (CORS問題) - 根據 W3C 的 RFC2616,OPTIONS無法被快取(not cacheable) - 不會有response body ### HEAD - 拿來檢查資料目前的狀態 - 判斷資料是否存在 - 應該回 status code 200 (OK) (RFC2616) 或是回跟 GET 目前一樣的 status code - 不會有response body ## HTTP 內定義的特殊方法 ### Idempotent Method - RFC2616 / RFC7231 (Sec 4.2.2) - 中文又稱作[冪(ㄇㄧˋ)等](https://zh.wikipedia.org/zh-tw/%E5%86%AA%E7%AD%89) - 在現在軟體工程中是不可或缺的一環 - 每一次產生的結果及影響都相同 - 在分散式系統 - GET / PUT / DELETE / HEAD / OPTIONS ### Safe Method - 定義在RFC2616 / RFC7231 - 不會產生任何副作用 - GET / HEAD / OPTIONS ### Cacheable Method - 定義在 IETF RFC 7231(Sec 4.2.3) RFC 7234 - 泛指可以被 cache 的請求 - 目前主要支援GET以及HEAD,定義上POST也可以被快取,但大多實作並不支援 - 框架不允許實作 ![](https://i.imgur.com/GWhPFry.jpg =400x) ### 為什麼DELETE method是idempoten - 兩派說法 - idempotent是在server上的狀態,不包含response,所以第一次刪除跟第二次刪除伺服器上的狀態都是刪除 - idempotent指的是server response必須一致,所以第一次跟第N次執行DELETE 結果都必須是200 or 204 (RFC 7231 Sec 4.2.2) ### 什麼是REST - 西元2000年發表 - 是共識,不是規範 - 玄學的一種 (有多玄?) - 講者表示:各公司所出的版本都不同 - 通常設計時會考慮語意化版本 - /v1/user - /v1/groups - 一般來說HTTP的REST就是RESTful - RESTful API 的設計一定是資源(resource)為出發點 - 格式為:`/{Resource}/{ResourceID}` - 資源單複數之稱的各種說法,根據Dr. Roy Fielding - 資源必須是「複數」的 - " Any information that can be named can be a resource. A resource is a conceptual mapping to a set of entities, not the entity that corresponds to the mapping at any particular point in time." [REST from Roy T. Fielding](https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm) - 所有東西都可以被當成資源 ### 錯誤/正確的範例 - `[GET] /v1/getUserList`(X) => `/v1/users`(O) - `[POST] /v1/createUser`(X) => `/v1/users`(O) #### 思考: Sign-in 是名詞嗎?[name=講者](此句說明?) ### REST 必須滿足[HATEOAS](HATEOAS)=>缺連結? - level 0 只使用單一endpoint去接收以及處理訊息 - level 1 ? - level 2 現在絕大多數開發者認識的REST,有resource以及resource id等概念 - level 3 加上了 hy-permedia - 可以考慮如JSON:API https://jsonapi.org/ ### REST的必要條件 - Client-Server Architecture - **Stateless** - 符合原子性(atomic)要求 - **Cacheability** - **Layered System** - Code On Demand - **Uniform Interface** ### 科技大廠怎麼設計API的(規範細節) - Case 1: Google - API 主要類型分做兩種 - Standard Method - Custom Method - 採用 nested resource 設計 - `users/*/messages/*` - `users/*/threads/*` - Custom Methods - Standard Methods 為主,Custom Methods 為輔 - 格式 - https://service.name/v1/some/resource/name:customVerb - 應該使用 POST 或是 GET 作為 HTTP 的呼叫方法 - 不應該使用 PATCH - 結尾(suffix)應該使用分號 - 應該遵循RFC規範 `[GET] /v3/event:batchGet` `[POST] /v3/events:clear` `[POST] /v3/events:cancel` - Case 2: Microsoft - API範例 - `https://adventure-works.com/orders` <= (GOOD) :heavy_check_mark: - `https://adventure-works.com/create-order` <= (BAD) :x: - 跟隨 Dr. Fielding 的所有規範,一定要是複數 - 不建議從關聯表為出發點設計 - 強調語意化版本 - Case 3: Facebook - object ID - facebook 的 API 都是object,使用相同種類(object)的 ID - 沒有REST的resource概念 - 主要由三個部分組成 - nodes - 主要對應resource id - /123(?)度 - edges - 在resource下的關聯 - /123/nodes - files - 取得欄位 - /123?filedid=id - me用來表示自己,會轉化成user id - `[GET] /me/photos` - `[GET] /me/videos` # 工商時間 Development Testing __ Monitoring 後端工程師PHP/ 前端工程師 --- ## 聊天區? 貓咪的名字? > 可能是「這是我的貓,你沒看過我給你看看」的哏,在圖片正上方有www >> 幫你支援 >> ![](https://i.imgur.com/F3UAcQH.png =200x) >> ![](https://i.imgur.com/QFXNPpp.jpg =300x) > <span style="color:red; font-size:30px">漢堡🍔超夯</span> > [color=#0F0] >> 我這個人很簡單 有貓就讚 ฅ^•ω•^ฅ >>> 有貓就是讚ฅ^•ﻌ•^ฅ 開戰 Backend ![](https://i.imgur.com/IsCeMtt.jpg =300x) ![](https://i.imgur.com/QrJ9695.jpg =300x) 突然又爆場了~~~ 好可怕~~ > 想起之前的場 怕沒人怎麼辦 把它塞爆就對了 > 去年R3也爆場阿 > 我好奇此時的R1 爆了沒? > 對耶 4點半了 玄學 是怎樣!!!!???XDDD > ![](https://i.imgur.com/8u8ROdN.jpg =400x) > (群組轉傳) > 因為總有人沒照著實作 > 通靈工程師~~ 理解了~ > ~~通靈是工程師必須的一環(X~~ > 只可意會不可言傳 > 一個REST各自表述 > 花生省魔術~ Google 的 Pattern 解決了我多年來對於非標準 Restful 動作命名方式的疑惑 :D ###### tags: `MOPCON 2020`

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully