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,
0:03 view models for the most part,
0:05 and we also touched on this one that I was calling services,
0:08 not web services or APIs, just services to the general larger application.
0:13 And I think the view model pattern is worth focusing on a little bit
0:17 here in the review. Remember,
0:18 with the view model pattern, it plays a lot of the same roles that maybe
0:21 Pydantic models do for the API endpoint.
0:24 Because Pydantic and FastAPI go so well together,
0:27 it makes sense that maybe we should just be using Pydantic models for this type of
0:32 exchange here but the problem is that Pydantic models, while
0:36 fantastic, they completely just give up if they run into a problem.
0:40 And we saw, one of the really important things was,
0:42 I'd like to be able to show
0:43 a form, let people type into that form,
0:46 try to submit it, if that doesn't work,
0:48 I need to reload the form with the old data.
0:50 Well, that's not how the Pydantic models work.
0:53 They just say you gave me something wrong,
0:55 go away. And so for that reason,
0:58 we have, a more forgiving pattern that is also quite similar,
1:02 but a little more manual called view models.
1:04 The idea is, there's a known set of data and data types and rules for validation
1:09 for an HTML template, the white thing here on the left.
1:12 And so let's create a Python class that knows about all that required data,
1:17 how to get it from the page,
1:19 how to convert it, how to exchange it,
1:21 what this validation rules are and completely separate that from the rest of the behavior.
1:26 So, for example, if our action method here was to register,
1:29 create a new user. We shouldn't have to worry about all that validation.
1:33 We should just be able to go: is it valid? No,
1:37 tell them to try again. Is it valid? Yes,
1:39 then create the user with the data that we got,
1:42 send them a welcome email, put them in the database, all the things that you
1:45 would expect to do, the actual business of this endpoint this view or action method rather
1:51 than all that validation and data exchange and conversion.
1:53 So that's the idea of these view models,
1:55 I think they're super, super valuable in web applications.
1:59 They make things like testing, the validation, all by itself without getting into web testing and
2:05 fake requests and all that kind of stuff really,
2:08 really easy. So this view model,
2:10 I think it's a great pattern.
2:11 Take it or leave it. But I suggest that you try it in your apps, I think it's highly valuable.