RESTful and HTTP APIs in Pyramid Transcripts
Chapter: Conclusion
Lecture: Lightning review: API view methods

Login or purchase this course to watch this video and the rest of the course contents.
0:01 Now we've got our app all configured, it's time to add some api views to it. So here we are going to create a method
0:07 that's going to respond to the route api_all cars, that's probably /api/autos, it's going to return its response as json
0:15 and it's only going to respond to get methods. So what do we do— well, we just go to the repository
0:20 and say give me the 25 latest cars and boom— here they are, and this worked because at this current early stage
0:26 the repository returned a list of dictionaries, not something more advanced like sqlalchemy objects, so we go and get the car from the database
0:33 return the list, and because the renderer is set to json, it automatically formats that to a list of json objects,
0:40 if it knows how to serialize them, which it does in this case. Now, if we want something more advanced
0:45 not just reading the cars but creating one, we could go to the same route but now we have post instead of get,
0:51 and in this case we're going to say request.json_body to convert the text that was submitted to us into a Python dictionary
0:58 by parsing it as json, that might have failed, so we'll send them a response 400, bad request, if that's the case;
1:04 otherwise, we'll actually try to create the car and we'll get back the car from the database
1:09 because we want the default values that got created in the database to be sent back so we'll say the response is 201 created,
1:16 oh yeah and here's the body of the car, if it happens to be an error— well, that's probably on us, 500, sorry about that.

Talk Python's Mastodon Michael Kennedy's Mastodon