From the course: Build REST APIs with FastAPI
Unlock this course with a free trial
Join today to access over 24,400 courses taught by industry experts.
Streaming responses - Python Tutorial
From the course: Build REST APIs with FastAPI
Streaming responses
Sometimes we have a lot of data to return, or maybe we're not sure how many items are coming, but we want to send them as they come. These are known as streaming responses. JSON does not have built-in support for streaming, but you can work with JSON lines or NDJSON. And the idea is that you send one JSON object per line, and the receiving side need to know that it reads a line, parse it as JSON with another line, and parse it as JSON, et cetera. When you do it in FastAPI, I'm going to import a streaming response. And what we're going to do is we're going to send events. So every event has a time, the user, the action the user did, and the URI. And now we have a query for the events. And this is a dummy query. Consider it may be a database query. And then for 10 times, we just create an event with the time, say, the user is Elliot. It read and tried to read the etc password. And then we yield it, which means that the query events is a generator. It returns one by one and you can run a…