跳至頁尾內容
產品對比

FastAPI Python(開發者使用指南)

FastAPI是一個現代化的、高效能的 Web 框架,用於使用 Python 建立 API。 它旨在易於使用和學習,同時提供強大的功能,例如自動驗證、序列化和自動互動式 API 文件。 此外,它還適用於任何模板引擎,並允許您使用專案所需的任何預設模板配置。

讓我們深入了解FastAPI的細節、特性以及如何有效地使用它。 本文稍後也會介紹IronPDF ,這是Iron Software出品的 PDF 產生 Python 套件。

FastAPI 的主要特性

1.高效能: FastAPI 是目前速度最快的 Python 框架之一,可與 Node.js 和 Go 相媲美,這得益於它使用 Starlette 構建 Web 部件,使用 Pydantic 構建資料部件。 2.易用性:設計直觀,可減少閱讀文件所花費的時間。 此框架利用標準的 Python 類型提示進行資料驗證和序列化。 3.自動互動式文件: FastAPI 使用 OpenAPI 和 JSON Schema 自動產生互動式 API 文檔,可透過 /docs(Swagger UI)和 /redoc(ReDoc)存取。 API 的任何更新都會自動反映在文件中。 4.編輯器支援:對 VS Code 等編輯器中的程式碼補全和類型檢查提供了出色的支持,從而加快了開發速度並減少了錯誤。 5.基於標準:它基於(並完全相容)API 的開放標準:OpenAPI 和 JSON Schema。

安裝

您可以使用 pip 安裝 FastAPI 和Uvicorn (一個 ASGI 伺服器):

pip install fastapi
pip install "uvicorn[standard]"
pip install fastapi
pip install "uvicorn[standard]"
SHELL

創建您的第一個 FastAPI 應用程式

以下是一個簡單的範例,可協助您快速上手 FastAPI 並透過使用者介面公開 Python 資料:

from fastapi import FastAPI

# Create a FastAPI 'app' instance
app = FastAPI()

# Root path operation
@app.get("/")
def read_root():
    return {"Hello": "World"}

# Path operation for items including query parameter 'q'
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}
from fastapi import FastAPI

# Create a FastAPI 'app' instance
app = FastAPI()

# Root path operation
@app.get("/")
def read_root():
    return {"Hello": "World"}

# Path operation for items including query parameter 'q'
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}
PYTHON

要運行該應用程序,請使用 Uvicorn:

uvicorn main:app --reload
uvicorn main:app --reload
SHELL

此命令將啟動開發伺服器,並在程式碼變更時自動重新載入。 您可以透過http://127.0.0.1:8000/docs存取互動式 API 文件。

進階功能

FastAPI 支援多種進階功能,使其適用於複雜的應用程式:

1.依賴注入: FastAPI 提供了一個強大的依賴注入系統,讓您可以乾淨且有效率地管理依賴項。 2.後台任務:您可以定義在回傳回應後執行的後台任務,這對於發送電子郵件或處理資料等任務非常有用。

  1. WebSocket: FastAPI 支援 WebSocket,可實現客戶端和伺服器之間的即時通訊。 4.安全性: FastAPI 包含用於處理安全性的工具,包括 OAuth2、JWT 令牌等。 5.資料庫整合: FastAPI 可以使用 SQLAlchemy 或 Tortoise-ORM 等函式庫輕鬆地與資料庫整合。

範例:建立 CRUD API

讓我們建立一個簡單的 CRUD(建立、讀取、更新、刪除)API 來管理專案。

1.定義資料模型:

from pydantic import BaseModel

# Define a Pydantic model for the item with default description and tax
class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None
from pydantic import BaseModel

# Define a Pydantic model for the item with default description and tax
class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None
PYTHON

2.建立 FastAPI 應用程式:

from fastapi import FastAPI, HTTPException

# Initialize 'app' instance and an empty 'items' dictionary
app = FastAPI()
items = {}

# Create operation: Add a new item
@app.post("/items/")
def create_item(item: Item):
    item_id = len(items) + 1
    items[item_id] = item
    return item

# Read operation: Retrieve an item by 'item_id'
@app.get("/items/{item_id}")
def read_item(item_id: int):
    if item_id not in items:
        raise HTTPException(status_code=404, detail="Item not found")
    return items[item_id]

# Update operation: Replace an existing item
@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
    if item_id not in items:
        raise HTTPException(status_code=404, detail="Item not found")
    items[item_id] = item
    return item

# Delete operation: Remove an item by 'item_id'
@app.delete("/items/{item_id}")
def delete_item(item_id: int):
    if item_id not in items:
        raise HTTPException(status_code=404, detail="Item not found")
    del items[item_id]
    return {"message": "Item deleted"}
from fastapi import FastAPI, HTTPException

# Initialize 'app' instance and an empty 'items' dictionary
app = FastAPI()
items = {}

# Create operation: Add a new item
@app.post("/items/")
def create_item(item: Item):
    item_id = len(items) + 1
    items[item_id] = item
    return item

# Read operation: Retrieve an item by 'item_id'
@app.get("/items/{item_id}")
def read_item(item_id: int):
    if item_id not in items:
        raise HTTPException(status_code=404, detail="Item not found")
    return items[item_id]

# Update operation: Replace an existing item
@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
    if item_id not in items:
        raise HTTPException(status_code=404, detail="Item not found")
    items[item_id] = item
    return item

# Delete operation: Remove an item by 'item_id'
@app.delete("/items/{item_id}")
def delete_item(item_id: int):
    if item_id not in items:
        raise HTTPException(status_code=404, detail="Item not found")
    del items[item_id]
    return {"message": "Item deleted"}
PYTHON

IronPDF簡介

FastAPI Python(開發者使用指南):圖 1

IronPDF是一個功能強大的 Python 庫,旨在從 HTML、CSS、圖像和 JavaScript 建立、編輯和簽署 PDF。 它提供商業級的效能,同時佔用記憶體極少。 主要特點包括:

HTML 轉 PDF

將 HTML 檔案、HTML 字串和 URL 轉換為 PDF。 例如,使用 Chrome PDF 渲染器將網頁渲染為 PDF。

跨平台支援

相容於各種 .NET 平台,包括 .NET Core、.NET Standard 和 .NET Framework。 它支援 Windows、Linux 和 macOS。

編輯和簽署

設定屬性,使用密碼和權限添加安全性,並為您的 PDF 應用數位簽章。

頁面模板和設置

使用頁首、頁尾、頁碼和可調整的邊距自訂 PDF。 支援響應式佈局和自訂紙張尺寸。

標準合規性

符合 PDF 標準,例如 PDF/A 和 PDF/UA。 支援 UTF-8 字元編碼,並可處理圖像、CSS 和字體等資源。

使用 IronPDF 和 FastAPI 產生 PDF 文檔

pip install fastapi
pip install ironPDF
pip install fastapi
pip install ironPDF
SHELL
from fastapi import FastAPI
from fastapi.responses import FileResponse
from ironpdf import *

# Apply your IronPDF license key
License.LicenseKey = "key"

# Initialize 'app' instance
app = FastAPI()

# Route for simple greeting
@app.get("/")
def read_root():
    return {"Hello": "IronPDF"}

# Route that reads items with path and query parameters
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}

# Route for generating a PDF document
@app.get("/pdf")
async def get_pdf(greet1: str = None, greet2: str = None):
    # Use ChromePdfRenderer to create PDF from HTML
    renderer = ChromePdfRenderer()
    content = "<h1>Document Generated using IronPDF with FastAPI GET</h1>"
    content += "<p> Demonstrate PDF generation using User Inputs</p>"
    content += f"<p>Greetings from: {greet1}</p>"
    content += f"<p>And Greetings from: {greet2}</p>"
    pdf = renderer.RenderHtmlAsPdf(content)

    # Save the PDF to a file
    pdf.SaveAs("fastapi.pdf")

    # Create a response with the generated PDF
    headers = {
        "Content-Disposition": "inline; filename=sample.pdf"
    }
    return FileResponse("fastapi.pdf", media_type="application/pdf", headers=headers)
from fastapi import FastAPI
from fastapi.responses import FileResponse
from ironpdf import *

# Apply your IronPDF license key
License.LicenseKey = "key"

# Initialize 'app' instance
app = FastAPI()

# Route for simple greeting
@app.get("/")
def read_root():
    return {"Hello": "IronPDF"}

# Route that reads items with path and query parameters
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}

# Route for generating a PDF document
@app.get("/pdf")
async def get_pdf(greet1: str = None, greet2: str = None):
    # Use ChromePdfRenderer to create PDF from HTML
    renderer = ChromePdfRenderer()
    content = "<h1>Document Generated using IronPDF with FastAPI GET</h1>"
    content += "<p> Demonstrate PDF generation using User Inputs</p>"
    content += f"<p>Greetings from: {greet1}</p>"
    content += f"<p>And Greetings from: {greet2}</p>"
    pdf = renderer.RenderHtmlAsPdf(content)

    # Save the PDF to a file
    pdf.SaveAs("fastapi.pdf")

    # Create a response with the generated PDF
    headers = {
        "Content-Disposition": "inline; filename=sample.pdf"
    }
    return FileResponse("fastapi.pdf", media_type="application/pdf", headers=headers)
PYTHON

程式碼解釋

此程式碼片段示範了 IronPDF 與 FastAPI 的集成,以根據使用者輸入動態生成 PDF 文檔,並將其作為可下載的回應提供。

1.設定許可證密鑰:套用 IronPDF 許可證密鑰以啟用其功能。

  1. FastAPI 初始化:初始化 FastAPI 實例( app )以處理 HTTP 請求。

3.基本路由處理程序:

  • read_root() : 存取根 URL ( / ) 時,傳回簡單的 JSON 訊息,表示"Hello IronPDF"。
  • read_item() : 接受item_id路徑參數和可選的q查詢參數。 傳回包含這些參數的 JSON 回應。
  1. PDF 生成路徑( /pdf ):
    • get_pdf() : 此非同步函數處理對/pdf端點的 GET 請求,帶有名為greet1greet2可選查詢參數。
    • 建立一個包含以下內容的 HTML 字串( content ):
      • 標明文件來源和用途的頁首。
      • 一段示範如何使用使用者輸入( greet1greet2 )產生 PDF 的段落。
    • 使用 IronPDF 中的ChromePdfRenderer()將 HTML 內容渲染成 PDF( pdf = renderer.RenderHtmlAsPdf(content) )。
    • 將產生的 PDF 儲存為"fastapi.pdf"( pdf.SaveAs(&quot;fastapi.pdf&quot;) )。

5.提供 PDF 檔:

  • 設定回應標頭,以指定應在瀏覽器中內嵌查看 PDF( &quot;Content-Disposition&quot;: &quot;inline; filename=sample.pdf&quot; )。
  • 建立一個指向產生的 PDF 檔案的FileResponse對象,並指定適當的媒體類型( &quot;application/pdf&quot; )。
  • 傳回FileResponse對象,當存取/pdf端點時,該對象會觸發 PDF 文件的下載。

此程式碼片段示範如何將 IronPDF 與 FastAPI 無縫集成,以根據使用者輸入動態產生和提供 PDF 文件。 它展示了將 HTML 內容轉換為 PDF 的功能,使其適用於需要透過 HTTP 即時產生和交付文件的應用。

輸出

下面顯示的是由 API 產生的 Swagger 輸出。

FastAPI Python(開發者使用方法):圖 2

PDF

FastAPI Python(開發者使用方法):圖 3

IronPDF 許可

IronPDF使用 Python 許可證金鑰運作。 IronPDF for Python 提供免費試用許可證金鑰,使用戶能夠在購買前體驗各項功能。

在使用 IronPDF 軟體包之前,請將許可證密鑰放在腳本的開頭:

from ironpdf import *
# Apply your license key
License.LicenseKey = "key"
from ironpdf import *
# Apply your license key
License.LicenseKey = "key"
PYTHON

結論

FastAPI是一個功能強大且易於使用的 Python API 建置框架。 FastAPI 具有高效能、自動產生文件和高級功能,對於初學者和經驗豐富的開發人員來說都是絕佳的選擇。 無論您是建立簡單的 API 還是複雜的 Web 應用程序,FastAPI 都能提供您成功所需的工具。

IronPDF是一個強大的 Python 庫,用於從 HTML 內容建立、操作和渲染 PDF 文件。 它提供 HTML 轉 PDF、互動式表單建立、PDF 操作(合併、分割)和文字擷取等功能。 非常適合輕鬆生成動態 PDF 並整合到各種 Python 應用程式中。

常見問題解答

如何在Python應用程式中將HTML內容轉換為PDF?

您可以使用 IronPDF 的ChromePdfRenderer將 HTML、CSS 和 JavaScript 內容轉換為 PDF 檔案。這使得它可以無縫整合到 Python 應用程式中,從而從 Web 內容生成 PDF 文件。

使用 FastAPI 建立 API 有哪些好處?

FastAPI 提供高效能、自動驗證、序列化和互動式 API 文件。它利用 Starlette 和 Pydantic 來確保速度和效率,可與 Node.js 和 Go 相媲美,同時支援 OpenAPI 等開放標準。

如何在 FastAPI 中提供 PDF 文件?

您可以使用 IronPDF 產生 PDF 文檔,然後使用 FastAPI 的FileResponse返回該文檔,從而在 FastAPI 中提供 PDF 服務。這種方法可讓您根據客戶端請求動態建立和提供 PDF 檔案。

FastAPI為何適合即時應用?

FastAPI 支援 WebSocket,可實現客戶端和伺服器之間的即時通信,因此是需要即時資料更新或即時互動的應用程式的理想選擇。

FastAPI 如何處理資料驗證和序列化?

FastAPI 使用 Pydantic 模型和標準的 Python 類型提示來處理資料驗證和序列化。這確保了輸入資料得到正確驗證並轉換為所需的格式,從而降低了出錯的機率。

FastAPI 提供哪些安全特性?

FastAPI 提供強大的安全功能,包括 OAuth2、JWT 驗證和依賴注入,使開發人員能夠以最少的努力建立安全的應用程式。

IronPDF 可以用於跨平台應用程式嗎?

是的,IronPDF 是一款跨平台軟體,支援 Windows、Linux 和 macOS。這使其成為希望將 PDF 生成功能整合到運行於不同作業系統上的應用程式中的開發人員的理想選擇。

FastAPI 如何提高開發人員的工作效率?

FastAPI 透過提供自動 API 文件、程式碼補全和類型檢查功能,提高了開發人員的效率。這減少了對大量手動文件的需求,並有助於在開發過程早期發現錯誤。

柯蒂斯·週
技術撰稿人

Curtis Chau擁有卡爾頓大學電腦科學學士學位,專長於前端開發,精通Node.js、TypeScript、JavaScript和React。他熱衷於打造直覺美觀的使用者介面,喜歡使用現代框架,並擅長撰寫結構清晰、視覺效果出色的使用者手冊。

除了開發工作之外,柯蒂斯對物聯網 (IoT) 也抱有濃厚的興趣,致力於探索硬體和軟體整合的創新方法。閒暇時,他喜歡玩遊戲和製作 Discord 機器人,將他對科技的熱愛與創造力結合。