Hướng dẫn python api parameters - tham số api python

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á .

.

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]:

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.

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.

Performance

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

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

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.

Ấ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.

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 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.

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}

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.

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"] # 

Bài Viết Liên Quan

Chủ Đề