Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit c01dc8b

Browse files
authored
📝 Update Library Agent Skill with streaming responses (#15024)
1 parent 8344d07 commit c01dc8b

1 file changed

Lines changed: 54 additions & 0 deletions

File tree

fastapi/.agents/skills/fastapi/SKILL.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -510,6 +510,60 @@ def read_items():
510510
return {"message": result}
511511
```
512512

513+
## Stream JSON Lines
514+
515+
To stream JSON Lines, declare the return type and use `yield` to return the data.
516+
517+
```python
518+
@app.get("/items/stream")
519+
async def stream_items() -> AsyncIterable[Item]:
520+
for item in items:
521+
yield item
522+
```
523+
524+
## Stream bytes
525+
526+
To stream bytes, declare a `response_class=` of `StreamingResponse` or a sub-class, and use `yield` to return the data.
527+
528+
```python
529+
from fastapi import FastAPI
530+
from fastapi.responses import StreamingResponse
531+
from app.utils import read_image
532+
533+
app = FastAPI()
534+
535+
536+
class PNGStreamingResponse(StreamingResponse):
537+
media_type = "image/png"
538+
539+
@app.get("/image", response_class=PNGStreamingResponse)
540+
def stream_image_no_async_no_annotation():
541+
with read_image() as image_file:
542+
yield from image_file
543+
```
544+
545+
prefer this over returning a `StreamingResponse` directly:
546+
547+
```python
548+
# DO NOT DO THIS
549+
550+
import anyio
551+
from fastapi import FastAPI
552+
from fastapi.responses import StreamingResponse
553+
from app.utils import read_image
554+
555+
app = FastAPI()
556+
557+
558+
class PNGStreamingResponse(StreamingResponse):
559+
media_type = "image/png"
560+
561+
562+
@app.get("/")
563+
async def main():
564+
return PNGStreamingResponse(read_image())
565+
```
566+
513567
## Use uv, ruff, ty
514568

515569
If uv is available, use it to manage dependencies.

0 commit comments

Comments
 (0)