Add reference (code API) docs with PEP 727, add subclass with custom docstrings for BackgroundTasks, refactor docs structure (#10392)

*  Add mkdocstrings and griffe-typingdoc to dependencies

* 🔧 Add mkdocstrings configs to MkDocs

* 📝 Add first WIP reference page

* ⬆️ Upgrade typing-extensions to the minimum version including Doc()

* 📝 Add docs to FastAPI parameters

* 📝 Add docstrings for OpenAPI docs utils

* 📝 Add docstrings for security utils

* 📝 Add docstrings for UploadFile

* 📝 Update docstrings in FastAPI class

* 📝 Add docstrings for path operation methods

* 📝 Add docstring for jsonable_encoder

* 📝 Add docstrings for exceptions

* 📝 Add docstsrings for parameter functions

* 📝 Add docstrings for responses

* 📝 Add docstrings for APIRouter

* ♻️ Sub-class BackgroundTasks to document it with docstrings

* 📝 Update usage of background tasks in dependencies

*  Update tests with new deprecation warnings

* 📝 Add new reference docs

* 🔧 Update MkDocs with new reference docs

*  Update pytest fixture, deprecation is raised only once

* 🎨 Update format for types in exceptions.py

* ♻️ Update annotations in BackgroundTask, `Annotated` can't take ParamSpec's P.args or P.kwargs

* ✏️ Fix typos caught by @pawamoy

* 🔧 Update and fix MkDocstrings configs from @pawamoy tips

* 📝 Update reference docs

* ✏️ Fix typos found by @pawamoy

*  Add HTTPX as a dependency for docs, for the TestClient

* 🔧 Update MkDocs config, rename websockets reference

* 🔇 Add type-ignores for Doc as the stubs haven't been released for mypy

* 🔥 Remove duplicated deprecated notice

* 🔇 Remove typing error for unreleased stub in openapi/docs.py

*  Add tests for UploadFile for coverage

* ⬆️ Upgrade griffe-typingdoc==0.2.2

* 📝 Refactor docs structure

* 🔨 Update README generation with new index frontmatter and style

* 🔨 Update generation of languages, remove from top menu, keep in lang menu

* 📝 Add OpenAPI Pydantic models

* 🔨 Update docs script to not translate Reference and Release Notes

* 🔧 Add reference for OpenAPI models

* 🔧 Update MkDocs config for mkdocstrings insiders

* 👷 Install mkdocstring insiders in CI for docs

* 🐛 Fix MkDocstrings insiders install URL

*  Move dependencies shared by docs and tests to its own requirements file

* 👷 Update cache keys for test and docs dependencies

* 📝 Remove no longer needed __init__ placeholder docstrings

* 📝 Move docstring for APIRouter to the class level (not __init__ level)

* 🔥 Remove no longer needed dummy placeholder __init__ docstring
This commit is contained in:
Sebastián Ramírez
2023-10-18 16:36:40 +04:00
committed by GitHub
parent 3fa44aabe3
commit 05ca41cfd1
60 changed files with 11791 additions and 988 deletions

View File

@@ -1,20 +1,141 @@
from typing import Any, Dict, Optional, Sequence, Type
from typing import Any, Dict, Optional, Sequence, Type, Union
from pydantic import BaseModel, create_model
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.exceptions import WebSocketException as WebSocketException # noqa: F401
from starlette.exceptions import WebSocketException as StarletteWebSocketException
from typing_extensions import Annotated, Doc # type: ignore [attr-defined]
class HTTPException(StarletteHTTPException):
"""
An HTTP exception you can raise in your own code to show errors to the client.
This is for client errors, invalid authentication, invalid data, etc. Not for server
errors in your code.
Read more about it in the
[FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/).
## Example
```python
from fastapi import FastAPI, HTTPException
app = FastAPI()
items = {"foo": "The Foo Wrestlers"}
@app.get("/items/{item_id}")
async def read_item(item_id: str):
if item_id not in items:
raise HTTPException(status_code=404, detail="Item not found")
return {"item": items[item_id]}
```
"""
def __init__(
self,
status_code: int,
detail: Any = None,
headers: Optional[Dict[str, str]] = None,
status_code: Annotated[
int,
Doc(
"""
HTTP status code to send to the client.
"""
),
],
detail: Annotated[
Any,
Doc(
"""
Any data to be sent to the client in the `detail` key of the JSON
response.
"""
),
] = None,
headers: Annotated[
Optional[Dict[str, str]],
Doc(
"""
Any headers to send to the client in the response.
"""
),
] = None,
) -> None:
super().__init__(status_code=status_code, detail=detail, headers=headers)
class WebSocketException(StarletteWebSocketException):
"""
A WebSocket exception you can raise in your own code to show errors to the client.
This is for client errors, invalid authentication, invalid data, etc. Not for server
errors in your code.
Read more about it in the
[FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).
## Example
```python
from typing import Annotated
from fastapi import (
Cookie,
FastAPI,
WebSocket,
WebSocketException,
status,
)
app = FastAPI()
@app.websocket("/items/{item_id}/ws")
async def websocket_endpoint(
*,
websocket: WebSocket,
session: Annotated[str | None, Cookie()] = None,
item_id: str,
):
if session is None:
raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Session cookie is: {session}")
await websocket.send_text(f"Message text was: {data}, for item ID: {item_id}")
```
"""
def __init__(
self,
code: Annotated[
int,
Doc(
"""
A closing code from the
[valid codes defined in the specification](https://datatracker.ietf.org/doc/html/rfc6455#section-7.4.1).
"""
),
],
reason: Annotated[
Union[str, None],
Doc(
"""
The reason to close the WebSocket connection.
It is UTF-8-encoded data. The interpretation of the reason is up to the
application, it is not specified by the WebSocket specification.
It could contain text that could be human-readable or interpretable
by the client code, etc.
"""
),
] = None,
) -> None:
super().__init__(code=code, reason=reason)
RequestErrorModel: Type[BaseModel] = create_model("Request")
WebSocketErrorModel: Type[BaseModel] = create_model("WebSocket")