Hướng dẫn python api deployment - triển khai python api

Lời mở đầu

Chào các bạn, hôm nay tôi xin giới thiệu với các bạn về 1 framework API mà tôi mới vọc vạch mấy tuần trước. Tại sao tôi lại giới thiệu framework này, âu cũng là do cái slogan của team này bắt mắt quá .

Hướng dẫn python api deployment - triển khai python api
.
Hướng dẫn python api deployment - triển khai python api

FastAPI framework, high performance, easy to learn, fast to code, ready for production

Vậy fastAPI là gì, mời các bạn đọc phần tiếp theo.

Khái niệm

FastApi là 1 web framework dùng để build API có hiệu năng cao, code dễ ẹc, đơn giản nhưng cũng hỗ trợ tốt cho việc làm sản phẩm.

Đặc điểm:

  • Fast: Hiệu suất cao ngang với NodeJS và Go.: Hiệu suất cao ngang với NodeJS và Go.
  • Fast to code: Code nhanh hơn, tốc độ code các features tăng khoảng 200 đến 300 %.: Code nhanh hơn, tốc độ code các features tăng khoảng 200 đến 300 %.
  • Fewer bugs: do đơn giản nên giảm số bugs của developper đến 40%.: do đơn giản nên giảm số bugs của developper đến 40%.
  • Intuitive: hỗ trợ code dễ hơn với tự động gợi ý, debug cần ít thời gian hơn so với trước.: hỗ trợ code dễ hơn với tự động gợi ý, debug cần ít thời gian hơn so với trước.
  • Easy: được thiết kế sao cho dễ dùng dễ học.: được thiết kế sao cho dễ dùng dễ học.
  • Short: Tối thiểu việc lặp code. Các tham số truyền vào có nhiều tính năng. Ít bugs.: Tối thiểu việc lặp code. Các tham số truyền vào có nhiều tính năng. Ít bugs.
  • Robust: hiệu năng mạnh mẽ, có thể tương tác API qua docs.: hiệu năng mạnh mẽ, có thể tương tác API qua docs.

Cài đặt

Yêu cầu: Python 3.6+.

FastAPI được build dựa trên OpenAPI (trước có tên Swagger), phần web được support bởi Starlette, còn phần data được support bởi Pydantic.

FastAPI CLI

Để cài đặt framework này trên Ubuntu, bạn cần phiên bản python ≥\geq 3.6.≥\geq 3.6.

pip install fastapi

Bạn cũng cần ASGI server khi deploy sản phẩm như Uvicorn hoặc Hypercorn.

pip install uvicorn

Nói sơ qua về ASGI 1 chút, ASGI kế thừa từ WSGI. Mà WSGI là 1 chuẩn giao tiếp giữa web server và Python application server. Trước thì có mod_python của Apache nhưng do không phát triển và không an toàn nên WSGI sinh ra. WSGI có những tác dụng như sau:

  • WSGI mang tính linh hoạt: dev có thể chuyển đổi thành phần web như chuyển từ Gunicorn sang uWSGI.
  • WSGI xử lý nhiều request cùng lúc thay webserver và quyết định request nào được chuyển tới application web. Hình minh họa chôm được ở trang (fullstackpython.com):

Hướng dẫn python api deployment - triển khai python api

Nếu như WSGI là tiêu chuẩn cho các

uvicorn main:app --host 0.0.0.0 --port 8000
8thì ASGI là tiêu chuẩn cho cả
uvicorn main:app --host 0.0.0.0 --port 8000
9 và
{
  "openapi": "3.0.2",
  "info": { "title": "FastAPI", "version": "0.1.0" },
  "paths": {
    "/": {
      "get": {
        "summary": "Root",
        "operationId": "root__get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": { "application/json": { "schema": {} } }
          }
        }
      }
    }
  }
}
0
{
  "openapi": "3.0.2",
  "info": { "title": "FastAPI", "version": "0.1.0" },
  "paths": {
    "/": {
      "get": {
        "summary": "Root",
        "operationId": "root__get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": { "application/json": { "schema": {} } }
          }
        }
      }
    }
  }
}
1. ASGI phù hợp với tất cả ứng dụng sử dụng WSGI do có cơ chế tương thích ngược.

Ok dông dài đủ rồi, chúng ta tiếp tục tìm hiểu xem FastAPI còn cung cấp những tiện ích gì nhé.

FastAPI Docs

Do based trên OpenAI mà trước đó có tên là Swagger nên FastAPI cung cấp doc có giao diện dễ nhìn, dễ sử dụng. Ví dụ minh họa:

Khi bật doc bằng local url

{
  "openapi": "3.0.2",
  "info": { "title": "FastAPI", "version": "0.1.0" },
  "paths": {
    "/": {
      "get": {
        "summary": "Root",
        "operationId": "root__get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": { "application/json": { "schema": {} } }
          }
        }
      }
    }
  }
}
2.
Hướng dẫn python api deployment - triển khai python api

1 giao diện khác của FastAPI docs

{
  "openapi": "3.0.2",
  "info": { "title": "FastAPI", "version": "0.1.0" },
  "paths": {
    "/": {
      "get": {
        "summary": "Root",
        "operationId": "root__get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": { "application/json": { "schema": {} } }
          }
        }
      }
    }
  }
}
3.
Hướng dẫn python api deployment - triển khai python api

Performance

Các bạn có thể test hiệu năng của các web framework trên trang này (https://www.techempower.com/benchmarks/)

Hướng dẫn python api deployment - triển khai python api

Optional Depencies

Do FastAPI based trên Pydantic và Starlette nên có hỗ trợ thêm 1 số thư viện có cũng được không có cũng không sao:

Pydantic:

  • {
      "openapi": "3.0.2",
      "info": { "title": "FastAPI", "version": "0.1.0" },
      "paths": {
        "/": {
          "get": {
            "summary": "Root",
            "operationId": "root__get",
            "responses": {
              "200": {
                "description": "Successful Response",
                "content": { "application/json": { "schema": {} } }
              }
            }
          }
        }
      }
    }
    
    4: JSON "parsing" nhanh hơn.
  • {
      "openapi": "3.0.2",
      "info": { "title": "FastAPI", "version": "0.1.0" },
      "paths": {
        "/": {
          "get": {
            "summary": "Root",
            "operationId": "root__get",
            "responses": {
              "200": {
                "description": "Successful Response",
                "content": { "application/json": { "schema": {} } }
              }
            }
          }
        }
      }
    }
    
    5: validate email.

Starlette:

  • {
      "openapi": "3.0.2",
      "info": { "title": "FastAPI", "version": "0.1.0" },
      "paths": {
        "/": {
          "get": {
            "summary": "Root",
            "operationId": "root__get",
            "responses": {
              "200": {
                "description": "Successful Response",
                "content": { "application/json": { "schema": {} } }
              }
            }
          }
        }
      }
    }
    
    6: khi bạn muốn tạo request, dùng
    {
      "openapi": "3.0.2",
      "info": { "title": "FastAPI", "version": "0.1.0" },
      "paths": {
        "/": {
          "get": {
            "summary": "Root",
            "operationId": "root__get",
            "responses": {
              "200": {
                "description": "Successful Response",
                "content": { "application/json": { "schema": {} } }
              }
            }
          }
        }
      }
    }
    
    7.
  • {
      "openapi": "3.0.2",
      "info": { "title": "FastAPI", "version": "0.1.0" },
      "paths": {
        "/": {
          "get": {
            "summary": "Root",
            "operationId": "root__get",
            "responses": {
              "200": {
                "description": "Successful Response",
                "content": { "application/json": { "schema": {} } }
              }
            }
          }
        }
      }
    }
    
    8: khi bạn muốn dùng
    {
      "openapi": "3.0.2",
      "info": { "title": "FastAPI", "version": "0.1.0" },
      "paths": {
        "/": {
          "get": {
            "summary": "Root",
            "operationId": "root__get",
            "responses": {
              "200": {
                "description": "Successful Response",
                "content": { "application/json": { "schema": {} } }
              }
            }
          }
        }
      }
    }
    
    9 hoặc
    from fastapi import FastAPI
    
    app = FastAPI()
    
    
    @app.get("/items/{item_id}")
    async def read_item(item_id):
        return {"item_id": item_id}
    
    0.
  • from fastapi import FastAPI
    
    app = FastAPI()
    
    
    @app.get("/items/{item_id}")
    async def read_item(item_id):
        return {"item_id": item_id}
    
    1: nếu bạn muốn dùng các mẫu config mặc định.
  • from fastapi import FastAPI
    
    app = FastAPI()
    
    
    @app.get("/items/{item_id}")
    async def read_item(item_id):
        return {"item_id": item_id}
    
    2: hỗ trợ "parsing" với request.form().
  • from fastapi import FastAPI
    
    app = FastAPI()
    
    
    @app.get("/items/{item_id}")
    async def read_item(item_id):
        return {"item_id": item_id}
    
    3: hỗ trợ
    from fastapi import FastAPI
    
    app = FastAPI()
    
    
    @app.get("/items/{item_id}")
    async def read_item(item_id):
        return {"item_id": item_id}
    
    4.
  • from fastapi import FastAPI
    
    app = FastAPI()
    
    
    @app.get("/items/{item_id}")
    async def read_item(item_id):
        return {"item_id": item_id}
    
    5: hỗ trợ
    from fastapi import FastAPI
    
    app = FastAPI()
    
    
    @app.get("/items/{item_id}")
    async def read_item(item_id):
        return {"item_id": item_id}
    
    6.

FastAPI:

  • from fastapi import FastAPI
    
    app = FastAPI()
    
    
    @app.get("/items/{item_id}")
    async def read_item(item_id):
        return {"item_id": item_id}
    
    7: ASGI server phục vụ cho ứng dụng của bạn.
  • from fastapi import FastAPI
    
    app = FastAPI()
    
    
    @app.get("/items/{item_id}")
    async def read_item(item_id):
        return {"item_id": item_id}
    
    8: nếu muốn dùng
    from fastapi import FastAPI
    
    app = FastAPI()
    
    
    @app.get("/items/{item_id}")
    async def read_item(item_id):
        return {"item_id": item_id}
    
    9.

Nếu muốn dùng hết thư viện trên thì bạn chỉ cần dùng 1 câu lệnh đơn giản.

pip install fastapi[all]

Hướng dẫn cơ bản

Create a simple API

Về cơ bản thì code dễ như ăn kẹo, bạn tạo 1 file

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}
0.

from fastapi import FastAPI #import class FastAPI() từ thư viện fastapi

app = FastAPI() # gọi constructor và gán vào biến app


@app.get("/") # giống flask, khai báo phương thức get và url
async def root(): # do dùng ASGI nên ở đây thêm async, nếu bên thứ 3 không hỗ trợ thì bỏ async đi
    return {"message": "Hello World"}

Sau đó chạy dòng code này để chạy app

uvicorn main:app --host 0.0.0.0 --port 8000

Hướng dẫn python api deployment - triển khai python api

P/S: nếu bạn làm trong môi trường phát triển có thể thêm

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}
1 để tự động restart sau khi thay đổi code.

Tiếp sau đó vào xem thử thành quả phát

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}
2.
Hướng dẫn python api deployment - triển khai python api

Ấn vào

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}
3 ->
from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}
4 -> API trả về response.
Hướng dẫn python api deployment - triển khai python api

Giao diện API này được thiết kế dựa trên OpenAPI. Bên đó có hẳn 1 khái niệm để define API gọi là "Schema". Nếu bạn tò mò thì vào link này

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}
5.

{
  "openapi": "3.0.2",
  "info": { "title": "FastAPI", "version": "0.1.0" },
  "paths": {
    "/": {
      "get": {
        "summary": "Root",
        "operationId": "root__get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": { "application/json": { "schema": {} } }
          }
        }
      }
    }
  }
}

Nói chung bạn chỉ cần 6 bước để tạo 1 API

  • Bước 1: import fastapi
  • Bước 2: tạo 1 instance của class FastAPI
  • Bước 3: tạo đường dẫn, bắt đầu từ
    from fastapi import FastAPI
    
    app = FastAPI()
    
    
    @app.get("/items/{item_id}")
    async def read_item(item_id: int):
        return {"item_id": item_id}
    
    6
  • Bước 4: khai báo phương thức HTTP: post, get, put, delete hay options, head, patch, trace
  • Bước 5: khai báo hàm
  • Bước 6: trả về content với format dict, list, str, int, ...

Path Parameters

Bạn có thể truyền param thông qua đường dẫn.

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id):
    return {"item_id": item_id}

Biến

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}
7 trên đường dẫn sẽ truyền vào hàm read_item với thông qua param trùng tên
from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}
7. Test thử
from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}
9.

Hướng dẫn python api deployment - triển khai python api

Path parameters with types

Bạn cũng có thể khai báo định dạng của param để trả về khi truyền biến đúng định dạng sẽ trả về giá trị.

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}

Hướng dẫn python api deployment - triển khai python api

Data validation

Còn nếu không đúng định dạng thì trả về thông báo. Mọi dữ liệu được validate đều dựa trên Pydantic.

Hướng dẫn python api deployment - triển khai python api

Order

Nếu bạn có khai báo đường dẫn trùng lặp như thế này:

from fastapi import FastAPI

app = FastAPI()


@app.get("/users/me") # <- here
async def read_user_me():
    return {"user_id": "the current user"}


@app.get("/users/{user_id}") # <- and here
async def read_user(user_id: str):
    return {"user_id": user_id}

Thì nhớ để theo thứ tự

from fastapi import FastAPI

app = FastAPI()


@app.get("/users/me") # <- here
async def read_user_me():
    return {"user_id": "the current user"}


@app.get("/users/{user_id}") # <- and here
async def read_user(user_id: str):
    return {"user_id": user_id}
0 trước rồi đến
from fastapi import FastAPI

app = FastAPI()


@app.get("/users/me") # <- here
async def read_user_me():
    return {"user_id": "the current user"}


@app.get("/users/{user_id}") # <- and here
async def read_user(user_id: str):
    return {"user_id": user_id}
1 sau, ngược lại nếu
from fastapi import FastAPI

app = FastAPI()


@app.get("/users/me") # <- here
async def read_user_me():
    return {"user_id": "the current user"}


@app.get("/users/{user_id}") # <- and here
async def read_user(user_id: str):
    return {"user_id": user_id}
1 ở trước thì sẽ nghĩ rằng "user_id" được nhận giá trị
from fastapi import FastAPI

app = FastAPI()


@app.get("/users/me") # <- here
async def read_user_me():
    return {"user_id": "the current user"}


@app.get("/users/{user_id}") # <- and here
async def read_user(user_id: str):
    return {"user_id": user_id}
3.

Path in path

FastAPI hỗ trợ khai báo đường dẫn trong đường dẫn API nhờ vào việc based Starlette.

/files/{file_path}
file_path = /home/johndoe/myfile.txt
=> /files/home/johndoe/myfile.txt
pip install uvicorn
0

Query Parameters

Nếu bạn truyền param dưới dạng key-value thì ở trong FastAPI có hỗ trợ với tên gọi "query" parameters.

pip install uvicorn
1

Kiểm tra ở link

from fastapi import FastAPI

app = FastAPI()


@app.get("/users/me") # <- here
async def read_user_me():
    return {"user_id": "the current user"}


@app.get("/users/{user_id}") # <- and here
async def read_user(user_id: str):
    return {"user_id": user_id}
4:
Hướng dẫn python api deployment - triển khai python api

Nếu bạn để ý skip và limit có format string khi làm đường dẫn nhưng một khi truyền về hàm thì sẽ ngay lập tức được convert từ string về int.

Optional parameters

Ngoài ra FastAPI cung cấp một cách khai báo

from fastapi import FastAPI

app = FastAPI()


@app.get("/users/me") # <- here
async def read_user_me():
    return {"user_id": "the current user"}


@app.get("/users/{user_id}") # <- and here
async def read_user(user_id: str):
    return {"user_id": user_id}
5 query parameters, mặc định là None.

pip install uvicorn
2

Như bạn thấy ở trên param truyền ở đường dẫn là

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}
7, nhưng trong hàm có thêm param
from fastapi import FastAPI

app = FastAPI()


@app.get("/users/me") # <- here
async def read_user_me():
    return {"user_id": "the current user"}


@app.get("/users/{user_id}") # <- and here
async def read_user(user_id: str):
    return {"user_id": user_id}
7. FastAPI chỉ sử dụng
from fastapi import FastAPI

app = FastAPI()


@app.get("/users/me") # <- here
async def read_user_me():
    return {"user_id": "the current user"}


@app.get("/users/{user_id}") # <- and here
async def read_user(user_id: str):
    return {"user_id": user_id}
8 để nhận định format của param còn
from fastapi import FastAPI

app = FastAPI()


@app.get("/users/me") # <- here
async def read_user_me():
    return {"user_id": "the current user"}


@app.get("/users/{user_id}") # <- and here
async def read_user(user_id: str):
    return {"user_id": user_id}
9 thì FastAPI không sử dụng, chỉ có tác dụng check lỗi nếu xảy ra.

Bạn có thể test bằng đường dẫn sau.

pip install uvicorn
3

Query parameter type conversion

Thay đổi giá trị mặc định bằng cách truyền giá trị trên đường dẫn.

pip install uvicorn
4

Trong trường hợp này

pip install uvicorn
5

Multiple path and query parameters

Với các đường dẫn lồng nhau, FastAPI biết param nào với param nào dựa trên tên param.

pip install uvicorn
6

Required query parameters

Đơn giản là bạn điền thiếu param trên đường dẫn sẽ báo lỗi

pip install uvicorn
7

Như hình dưới này, tôi chỉ truyền vào giá trị của

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}
7 còn giá trị của
/files/{file_path}
file_path = /home/johndoe/myfile.txt
=> /files/home/johndoe/myfile.txt
1 thì không nên sinh ra lỗi.
Hướng dẫn python api deployment - triển khai python api

Request Body

  • Request body: người dùng gửi request từ browser đến API.
  • Response body: dựa trên request, APi trả về response cho người dùng.

Để khai báo format của request body, bạn cần sử dụng

/files/{file_path}
file_path = /home/johndoe/myfile.txt
=> /files/home/johndoe/myfile.txt
2 models. P/S: nhắc nhở khi send request cần sử dụng phương thức POST, nếu dùng phương thức GET thì bạn sẽ bị lộ thông tin trên URL => tính bảo mật không cao.

Pydantic Models

pip install uvicorn
8

Ví dụ về 1 instance của class Item.

pip install uvicorn
9

Do

/files/{file_path}
file_path = /home/johndoe/myfile.txt
=> /files/home/johndoe/myfile.txt
3 và
/files/{file_path}
file_path = /home/johndoe/myfile.txt
=> /files/home/johndoe/myfile.txt
4 có giá trị None nên bạn có thể không cần thêm vào cũng được.

pip install fastapi[all]
0

Dựa trên việc import Pydantic module, FastAPI hỗ trợ:

  • Đọc request body dưới dạng Json.
  • Chuyển đổi định dạng biến.
  • Validate dữ liệu
  • Khai báo format mặc định của request body, class Item trên là 1 ví dụ.
  • Gen JSON Schema cho model của bạn
  • Schema sẽ được gen thành UI của OpenAI doc.

Use model

Trong hàm create_item, bạn có thể tùy biến các biến của class Item, đơn giản như việc tính phí chịu thuế bằng cách tính tổng

/files/{file_path}
file_path = /home/johndoe/myfile.txt
=> /files/home/johndoe/myfile.txt
5 và
/files/{file_path}
file_path = /home/johndoe/myfile.txt
=> /files/home/johndoe/myfile.txt
6 như bên dưới.

pip install fastapi[all]
1

Request body + path parameters

FastAPI hỗ trợ khai báo tham số URL và request body cùng lúc, framework sẽ biết tham số nào truyền từ đường dẫn và tham số nào lấy từ request.

pip install fastapi[all]
2

Hướng dẫn python api deployment - triển khai python api
P/S: tương tự như trên bạn có thể thêm tham số URL, tham số query và request body cùng lúc.

Query Parameters and String Validations

Ở phần trước chúng ta đã biết khái niệm của query parameter rồi, lạ 1 loại param có cũng được không có cũng không sao. Param này có attribute là

from fastapi import FastAPI

app = FastAPI()


@app.get("/users/me") # <- here
async def read_user_me():
    return {"user_id": "the current user"}


@app.get("/users/{user_id}") # <- and here
async def read_user(user_id: str):
    return {"user_id": user_id}
9, nhưng độ dài bị giới hạn không vượt quá 50 ký tự. Nên FastAPI cung cấp class Query.

pip install fastapi[all]
3

Câu lệnh

/files/{file_path}
file_path = /home/johndoe/myfile.txt
=> /files/home/johndoe/myfile.txt
8 cũng tương tự
/files/{file_path}
file_path = /home/johndoe/myfile.txt
=> /files/home/johndoe/myfile.txt
9 nhưng Query cung cấp các param khác như max_lenght, min_lenght, regex, ... Bạn có thể tăng giới hạn ký tự thành 250 như thế này chỉ việc thay đổi giá trị tham số. (Mặc định của max_lenght là 50)

pip install fastapi[all]
4

Query parameter list / multiple values

Ngoài định dạng string và integer, FastAPI còn hỗ trợ type List.

pip install fastapi[all]
5
pip install fastapi[all]
6

Response body mà API trả về.

pip install fastapi[all]
7

API cũng được cập nhật theo. P/S: bạn cũng có thể thay

pip install uvicorn
00 thành
pip install uvicorn
01 như thế này.
Hướng dẫn python api deployment - triển khai python api
P/S: bạn cũng có thể thay
pip install uvicorn
00 thành
pip install uvicorn
01 như thế này.

pip install fastapi[all]
8

Query còn 1 vài param nữa nhưng không quá quan trọng, bạn có thể vào doc của FastAPI để tìm hiểu chi tiết.

Các param mà Query cung cấp:

Metadata

  • pip install uvicorn
    
    02: tên khác của param
  • pip install uvicorn
    
    03: metadata đặt tên param
  • /files/{file_path}
    file_path = /home/johndoe/myfile.txt
    => /files/home/johndoe/myfile.txt
    
    3: metadata giới thiệu param
  • pip install uvicorn
    
    05: khi bạn chán param nào thì thêm vào để người dùng biết là bạn không còn sử dụng param đó nữa

Validation cho string:

  • pip install uvicorn
    
    06
  • pip install uvicorn
    
    07
  • pip install uvicorn
    
    08

Path Parameters and Numeric Validations

Query parameters có class Query để khai báo metadata và validations, Path parameters có class Pass với cơ chế tương tự.

Thêm

pip install uvicorn
03 metadata cho path param
from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}
7:

pip install fastapi[all]
9

Number validations: greater than or equal

Chúng ta không chỉ có thể validate string mà còn validate được number.

Với param

pip install uvicorn
11 của class Path,
from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}
7 bắt buộc phải là 1 số lớn hơn hoặc bằng 1

from fastapi import FastAPI #import class FastAPI() từ thư viện fastapi

app = FastAPI() # gọi constructor và gán vào biến app


@app.get("/") # giống flask, khai báo phương thức get và url
async def root(): # do dùng ASGI nên ở đây thêm async, nếu bên thứ 3 không hỗ trợ thì bỏ async đi
    return {"message": "Hello World"}
0

Number validations: greater than and less than or equal

Tương tự với

pip install uvicorn
13,
from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}
7 bắt buộc phải là 1 số nhỏ hơn hoặc bằng 100.

from fastapi import FastAPI #import class FastAPI() từ thư viện fastapi

app = FastAPI() # gọi constructor và gán vào biến app


@app.get("/") # giống flask, khai báo phương thức get và url
async def root(): # do dùng ASGI nên ở đây thêm async, nếu bên thứ 3 không hỗ trợ thì bỏ async đi
    return {"message": "Hello World"}
1

P/S: Number validations không chỉ hỗ trợ type integer mà còn hỗ trợ cho type float.

from fastapi import FastAPI #import class FastAPI() từ thư viện fastapi

app = FastAPI() # gọi constructor và gán vào biến app


@app.get("/") # giống flask, khai báo phương thức get và url
async def root(): # do dùng ASGI nên ở đây thêm async, nếu bên thứ 3 không hỗ trợ thì bỏ async đi
    return {"message": "Hello World"}
2
  • pip install uvicorn
    
    15: >\gt>\gt
  • pip install uvicorn
    
    16: ≥\ge≥\ge
  • pip install uvicorn
    
    17: <\lt
  • pip install uvicorn
    
    18: ≤ \le≤ \le

Body

Multiple Parameters

Đơn giản là FastAPI hỗ trợ tạo format cho request body, bạn có thể dùng không chỉ 1 mà là N Pydantic model như ví dụ dưới, tôi khai báo 2 class

pip install uvicorn
19 và
pip install uvicorn
20 tương ứng 2 Pydantic model.

from fastapi import FastAPI #import class FastAPI() từ thư viện fastapi

app = FastAPI() # gọi constructor và gán vào biến app


@app.get("/") # giống flask, khai báo phương thức get và url
async def root(): # do dùng ASGI nên ở đây thêm async, nếu bên thứ 3 không hỗ trợ thì bỏ async đi
    return {"message": "Hello World"}
3
from fastapi import FastAPI #import class FastAPI() từ thư viện fastapi

app = FastAPI() # gọi constructor và gán vào biến app


@app.get("/") # giống flask, khai báo phương thức get và url
async def root(): # do dùng ASGI nên ở đây thêm async, nếu bên thứ 3 không hỗ trợ thì bỏ async đi
    return {"message": "Hello World"}
4

Singular values in body

Bạn cũng có thể thêm define 1 body cho chỉ 1 giá trị mà không cần khai báo class, giả dụ ở đây tôi thêm 1 param là

pip install uvicorn
21 có type là int và cũng là 1 key nằm trong json body, nên khi post data thì bạn cũng phải khai báo giá trị cho
pip install uvicorn
21.

from fastapi import FastAPI #import class FastAPI() từ thư viện fastapi

app = FastAPI() # gọi constructor và gán vào biến app


@app.get("/") # giống flask, khai báo phương thức get và url
async def root(): # do dùng ASGI nên ở đây thêm async, nếu bên thứ 3 không hỗ trợ thì bỏ async đi
    return {"message": "Hello World"}
5
from fastapi import FastAPI #import class FastAPI() từ thư viện fastapi

app = FastAPI() # gọi constructor và gán vào biến app


@app.get("/") # giống flask, khai báo phương thức get và url
async def root(): # do dùng ASGI nên ở đây thêm async, nếu bên thứ 3 không hỗ trợ thì bỏ async đi
    return {"message": "Hello World"}
6

Multiple body params and query

Nói đơn giản là kết hợp multiple body param với query param.

from fastapi import FastAPI #import class FastAPI() từ thư viện fastapi

app = FastAPI() # gọi constructor và gán vào biến app


@app.get("/") # giống flask, khai báo phương thức get và url
async def root(): # do dùng ASGI nên ở đây thêm async, nếu bên thứ 3 không hỗ trợ thì bỏ async đi
    return {"message": "Hello World"}
7

Field

Để validate data hoặc thêm metadata trong 1 class giả dụ

pip install uvicorn
19 chẳng hạn, bạn cần import
pip install uvicorn
24 operation function từ module
pip install uvicorn
25.

from fastapi import FastAPI #import class FastAPI() từ thư viện fastapi

app = FastAPI() # gọi constructor và gán vào biến app


@app.get("/") # giống flask, khai báo phương thức get và url
async def root(): # do dùng ASGI nên ở đây thêm async, nếu bên thứ 3 không hỗ trợ thì bỏ async đi
    return {"message": "Hello World"}
8

Như đoạn code ở trên param

/files/{file_path}
file_path = /home/johndoe/myfile.txt
=> /files/home/johndoe/myfile.txt
3 có metadata là title, với length không vượt quá 300 từ, hay như param
pip install uvicorn
27 không được nhỏ hơn 0 và có metadata là description.

Nested Models

Ngoài các kiểu int, float, str, bạn còn có thể thêm kiểu list hay set như dưới đây.

from fastapi import FastAPI #import class FastAPI() từ thư viện fastapi

app = FastAPI() # gọi constructor và gán vào biến app


@app.get("/") # giống flask, khai báo phương thức get và url
async def root(): # do dùng ASGI nên ở đây thêm async, nếu bên thứ 3 không hỗ trợ thì bỏ async đi
    return {"message": "Hello World"}
9

Với cách khai báo trên, khi post bạn truyền param là 1 list, nhưng với cách khai báo trên thì list này sẽ không xác định kiểu định dạng của từng phần tử trong list. Không sao bởi Python có module

pip install uvicorn
28 hỗ trợ bạn khai báo param là list xác định kiểu định dạng của từng phần tử.

uvicorn main:app --host 0.0.0.0 --port 8000
0

Tương tự với

pip install uvicorn
28, bạn có thể thêm
pip install uvicorn
30.

uvicorn main:app --host 0.0.0.0 --port 8000
1

Ngoài ra các kiểu normal như str, int, float, ... FastAPI cũng hỗ trợ thêm các định dạng phức tạp và đa dạng hơn, giả sử định dạng

pip install uvicorn
31 kế thừa từ định dạng
from fastapi import FastAPI

app = FastAPI()


@app.get("/users/me") # <- here
async def read_user_me():
    return {"user_id": "the current user"}


@app.get("/users/{user_id}") # <- and here
async def read_user(user_id: str):
    return {"user_id": user_id}
8. Để biết thêm chi tiết mời check link này (https://pydantic-docs.helpmanual.io/usage/types/).

  • Tiếp sau đây tôi sẽ giới thiệu các bạn cách khai báo 1 model lồng trong 1 model khác như thế nào.

Giả sử tôi có 2 class Images và Item.

uvicorn main:app --host 0.0.0.0 --port 8000
2

Tôi muốn class Images nằm trong class Item như thế này.

uvicorn main:app --host 0.0.0.0 --port 8000
3

Bạn chỉ cần thêm 1 dòng code vào class Item. Easy !

uvicorn main:app --host 0.0.0.0 --port 8000
4

Bạn cũng có thể tùy biến định dạng của Pydantic models là list hoặc set chẳng hạn.

uvicorn main:app --host 0.0.0.0 --port 8000
5

Và đây là kết quả.

uvicorn main:app --host 0.0.0.0 --port 8000
6

Trên lý thuyết bạn có thể lặp đi lặp lại các models lồng nhau như sau. Class Image nằm trong class Item, class Item thì lại nằm trong class Offer.

uvicorn main:app --host 0.0.0.0 --port 8000
7

Hướng dẫn python api deployment - triển khai python api

Kết luận

Do FastAPI là 1 framework API mới, có rất nhiều tính năng nên tôi chia ra thành nhiều phần (căn bản do không đủ kiên nhẫn để viết ). Ở đây tôi sẽ chỉ liệt kê các tính năng quan trọng dùng nhiều trước rồi sau đó sẽ nâng cao lên trong các phần tiếp theo. Bạn cũng có thể xem thẳng trên doc của fastapi. Link tham khảo here:

Hướng dẫn python api deployment - triển khai python api
). Ở đây tôi sẽ chỉ liệt kê các tính năng quan trọng dùng nhiều trước rồi sau đó sẽ nâng cao lên trong các phần tiếp theo. Bạn cũng có thể xem thẳng trên doc của fastapi. Link tham khảo here:

  • https://fastapi.tiangolo.com/tutorial/