RESTful and HTTP APIs in Pyramid Transcripts
Chapter: Validation with view models
Lecture: Concept: View models

Login or purchase this course to watch this video and the rest of the course contents.
0:01 We saw that our API method once we tried to add validation and proper object creation, really blew up crazy so it was view models to the rescue,
0:10 and in the end what we did was we created a view model base class that held a few things, and one is the errors— oh and we could have also,
0:18 I have it here in the slides for you but we didn't do it in the demo was we could have the error status, so like 400 versus 404 versus things like that
0:27 if you want to return different values, we'll see how to do that. So we have the errors, the error status and the error text or error message,
0:33 we could put all those into a view model base and then, we create our view models based on that base class. So here we have an update car view model
0:42 in our demo we wrote a create car, here's what update might look like, so update, you have to have the car you're going to update
0:47 and the data that you are using, so the post to data dictionary in this case, we are holding the dictionary, the car id and not the car
0:55 and then we call compute details we're actually going to go and find the car by id
0:58 and if we don't find it, we'll say hey, we couldn't find that car that's an error message the error status is 404, right because the car wasn't found;
1:07 then later, we'll go and actually create the car and do validation and say well, if some of the validation fails, that's a 400 error
1:15 and the various errors in the submitted data that you got to deal with those are the problems right, like the price was required,
1:23 the year was negative, things like that. Now with this in place, if we go back and look at our API method
1:30 you can see it's much, much cleaner, so in the gray section we're juggling a little bit of the inputs we have to in the web framework
1:37 all of that validation is focused just in that little reddish area in the middle
1:41 and no matter how much we add to this, it doesn't really expand or grow this and then the thing we're actually trying to do,
1:49 update the car or create the car happens very clearly here, so you can see you we're using the view model,
1:54 we're creating it and passing the data it needs to get started calling compute details, if there were errors
1:58 you respond with the error status and the error text.

Talk Python's Mastodon Michael Kennedy's Mastodon