| 1 |
from fastapi import FastAPI |
| 2 |
from fastapi.responses import JSONResponse |
| 3 |
from fastapi.testclient import TestClient |
| 4 |
from inline_snapshot import snapshot |
| 5 |
from pydantic import BaseModel |
| 6 |
|
| 7 |
app = FastAPI() |
| 8 |
|
| 9 |
|
| 10 |
class JsonApiResponse(JSONResponse): |
| 11 |
media_type = "application/vnd.api+json" |
| 12 |
|
| 13 |
|
| 14 |
class Error(BaseModel): |
| 15 |
status: str |
| 16 |
title: str |
| 17 |
|
| 18 |
|
| 19 |
class JsonApiError(BaseModel): |
| 20 |
errors: list[Error] |
| 21 |
|
| 22 |
|
| 23 |
@app.get( |
| 24 |
"/a/{id}", |
| 25 |
response_class=JsonApiResponse, |
| 26 |
responses={422: {"description": "Error", "model": JsonApiError}}, |
| 27 |
) |
| 28 |
async def a(id): |
| 29 |
pass # pragma: no cover |
| 30 |
|
| 31 |
|
| 32 |
client = TestClient(app) |
| 33 |
|
| 34 |
|
| 35 |
def test_openapi_schema(): |
| 36 |
response = client.get("/openapi.json") |
| 37 |
assert response.status_code == 200, response.text |
| 38 |
assert response.json() == snapshot( |
| 39 |
{ |
| 40 |
"openapi": "3.1.0", |
| 41 |
"info": {"title": "FastAPI", "version": "0.1.0"}, |
| 42 |
"paths": { |
| 43 |
"/a/{id}": { |
| 44 |
"get": { |
| 45 |
"responses": { |
| 46 |
"422": { |
| 47 |
"description": "Error", |
| 48 |
"content": { |
| 49 |
"application/vnd.api+json": { |
| 50 |
"schema": { |
| 51 |
"$ref": "#/components/schemas/JsonApiError" |
| 52 |
} |
| 53 |
} |
| 54 |
}, |
| 55 |
}, |
| 56 |
"200": { |
| 57 |
"description": "Successful Response", |
| 58 |
"content": {"application/vnd.api+json": {"schema": {}}}, |
| 59 |
}, |
| 60 |
}, |
| 61 |
"summary": "A", |
| 62 |
"operationId": "a_a__id__get", |
| 63 |
"parameters": [ |
| 64 |
{ |
| 65 |
"required": True, |
| 66 |
"schema": {"title": "Id"}, |
| 67 |
"name": "id", |
| 68 |
"in": "path", |
| 69 |
} |
| 70 |
], |
| 71 |
} |
| 72 |
} |
| 73 |
}, |
| 74 |
"components": { |
| 75 |
"schemas": { |
| 76 |
"Error": { |
| 77 |
"title": "Error", |
| 78 |
"required": ["status", "title"], |
| 79 |
"type": "object", |
| 80 |
"properties": { |
| 81 |
"status": {"title": "Status", "type": "string"}, |
| 82 |
"title": {"title": "Title", "type": "string"}, |
| 83 |
}, |
| 84 |
}, |
| 85 |
"JsonApiError": { |
| 86 |
"title": "JsonApiError", |
| 87 |
"required": ["errors"], |
| 88 |
"type": "object", |
| 89 |
"properties": { |
| 90 |
"errors": { |
| 91 |
"title": "Errors", |
| 92 |
"type": "array", |
| 93 |
"items": {"$ref": "#/components/schemas/Error"}, |
| 94 |
} |
| 95 |
}, |
| 96 |
}, |
| 97 |
} |
| 98 |
}, |
| 99 |
} |
| 100 |
) |