Full Web Apps with FastAPI Transcripts
Chapter: Course conclusion and review
Lecture: View model pattern

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Our next major area that we focused on were two design patterns, view models for the most part,
0:06 and we also touched on this one that I was calling services, not web services or APIs, just services to the general larger application.
0:14 And I think the view model pattern is worth focusing on a little bit here in the review. Remember,
0:19 with the view model pattern, it plays a lot of the same roles that maybe Pydantic models do for the API endpoint.
0:25 Because Pydantic and FastAPI go so well together, it makes sense that maybe we should just be using Pydantic models for this type of
0:33 exchange here but the problem is that Pydantic models, while fantastic, they completely just give up if they run into a problem.
0:41 And we saw, one of the really important things was, I'd like to be able to show a form, let people type into that form,
0:47 try to submit it, if that doesn't work, I need to reload the form with the old data. Well, that's not how the Pydantic models work.
0:54 They just say you gave me something wrong, go away. And so for that reason, we have, a more forgiving pattern that is also quite similar,
1:03 but a little more manual called view models. The idea is, there's a known set of data and data types and rules for validation
1:10 for an HTML template, the white thing here on the left. And so let's create a Python class that knows about all that required data,
1:18 how to get it from the page, how to convert it, how to exchange it,
1:22 what this validation rules are and completely separate that from the rest of the behavior. So, for example, if our action method here was to register,
1:30 create a new user. We shouldn't have to worry about all that validation. We should just be able to go: is it valid? No,
1:38 tell them to try again. Is it valid? Yes, then create the user with the data that we got,
1:43 send them a welcome email, put them in the database, all the things that you
1:46 would expect to do, the actual business of this endpoint this view or action method rather than all that validation and data exchange and conversion.
1:54 So that's the idea of these view models, I think they're super, super valuable in web applications.
2:00 They make things like testing, the validation, all by itself without getting into web testing and fake requests and all that kind of stuff really,
2:09 really easy. So this view model, I think it's a great pattern.
2:12 Take it or leave it. But I suggest that you try it in your apps, I think it's highly valuable.

Talk Python's Mastodon Michael Kennedy's Mastodon