Coverage for docs_src/path_operation_advanced_configuration/tutorial007.py: 100%

20 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-08-08 03:53 +0000

1from typing import List 1abcde

2 

3import yaml 1abcde

4from fastapi import FastAPI, HTTPException, Request 1abcde

5from pydantic import BaseModel, ValidationError 1abcde

6 

7app = FastAPI() 1abcde

8 

9 

10class Item(BaseModel): 1abcde

11 name: str 1abcde

12 tags: List[str] 1abcde

13 

14 

15@app.post( 1abcde

16 "/items/", 

17 openapi_extra={ 

18 "requestBody": { 

19 "content": {"application/x-yaml": {"schema": Item.model_json_schema()}}, 

20 "required": True, 

21 }, 

22 }, 

23) 

24async def create_item(request: Request): 1abcde

25 raw_body = await request.body() 1abcde

26 try: 1abcde

27 data = yaml.safe_load(raw_body) 1abcde

28 except yaml.YAMLError: 1abcde

29 raise HTTPException(status_code=422, detail="Invalid YAML") 1abcde

30 try: 1abcde

31 item = Item.model_validate(data) 1abcde

32 except ValidationError as e: 1abcde

33 raise HTTPException(status_code=422, detail=e.errors(include_url=False)) 1abcde

34 return item 1abcde