RESTful and HTTP APIs in Pyramid Transcripts
Chapter: Conclusion
Lecture: Lightning review: View models

Login or purchase this course to watch this video and the rest of the course contents.
0:01 After content negotiation and the different renderers we added validation to our api which was sorely missing up until this point,
0:08 but once we did, the actual validation code simply overwhelmed the api code and the important code if you will, by just totally filling up
0:17 so we said let's create this abstraction called a view model whose job is to do the validation, to do the transformation
0:23 from original object into rich Python objects and so on. So here, after having a super bloated update auto method,
0:30 we condensed it back down, so we're doing the standard web stuff in gray
0:34 so we're getting the request.json_body and we have to do that in the api method
0:38 because there's not really a good way to do that without passing the request itself
0:42 so we just go ahead and say fine we'll have to do this here, a little bit of web work and then we create our view model, we give it the initial data,
0:48 call compute details and then it populates its errors response which is a list of problems that may have encountered
0:55 and if it has one, it just says hey there's some kind of problem like 400 bad response, 404 missing, 403 permission denied, whatever
1:02 and it sends the error text and the status back. All right so that orange line or red line section in the middle
1:09 no matter how much validation we add it's going to stay that simple and if we want to test the validation,
1:15 we don't need to do that by mocking of the web request in the database we just give it this object and we can test that on its own.
1:21 If we make it through that, then we're really down to what we wanted to do in the first place,
1:26 take a car, update the database and either say that worked or it didn't. So here we're returning the error 400,
1:31 because the repository was doing some validation as well but it could also be 500, we need to be more careful
1:40 about the exception type that we're catching so like a database exception probably our fault,
1:45 like couldn't connect, some sort of other validation exception, well maybe we do 400 here.


Talk Python's Mastodon Michael Kennedy's Mastodon