在實際的開發中呢,我們可能有些接口呢,不能對比進行開放,比如說我們內部的一些監控的接口,那么我們肯定想着如何在接口文檔中進行屏蔽,那么我們看下應該如何實現呢。
@app.get("/legacy/", include_in_schema=False) def get_legacy_data(response: Response): headers = {"X-Cat": "leizi", "Content-Language": "en-US"} data = """<?xml version="1.0"?> <shampoo> <Header> Apply shampoo here. </Header> <Body> You'll have to use soap here. </Body>r </shampoo> """ response.set_cookie(key="message", value="hello") return Response(content=data, media_type="application/xml", headers=headers)
其實很簡單,只需要配置
include_in_schema=False
即可。那么我們看下接口文檔是否有這個接口呢
是沒有在接口的文檔中展示的,只能供我們自己內部直接調用。我們直接去訪問。
接口可以正常返回的。
docstring 的高級描述
路徑操作函數 的 docstring 中用於 OpenAPI 的行數。
添加一個 \f (一個「換頁」的轉義字符)可以使 FastAPI 在那一位置截斷用於 OpenAPI 的輸出。
我們看下在接口中的具體實現
# 新建用戶 @usersRouter.post("/users/", tags=["users"], response_model=Users) def create_user(user: UserCreate, db: Session = Depends(get_db)): """ - **email**: 用戶的郵箱 - **password**: 用戶密碼 """ db_crest = get_user_emai(db, user.email) if not db_crest: return db_create_user(db=db, user=user) raise HTTPException(status_code=200, detail="賬號不能重復")
我們看下最后會返回什么。
我們可以看到,在接口文檔中,我們去描述了我們的參數。文檔內正常展示了,那么我們可以用這個,對接口的參數進行一些描述后,就可以展示在我們對外的接口文檔中,方便去理解每個字段。
文章首發在公眾號,歡迎關注。