RESTful and HTTP APIs in Pyramid Transcripts
Chapter: A nearly RESTful service
Lecture: The problem: JSON renderer for custom types
0:01 Now you might feel like we've done everything there is to do
0:03 with this json renderer, the built in one,
0:05 but, there is a really important question we have to address before we move on.
0:09 So, using it is straightforward as we've seen,
0:11 we just set the renderer to json, and don't have to do anything,
0:15 pyramid already knows about that, that's cool,
0:17 and then we just return some object that is serializable
0:21 as an object for the json renderer,
0:24 so basically if you can use the json module in Python,
0:27 to serialize this, then it will work fine here, okay.
0:30 Now, what happens if that cars object
0:34 that we were returning from that method and letting the renderer serialize
0:37 what if it contains some kind of custom type, right,
0:41 like an entity you might get back from the database or something like that,
0:44 well, maybe everything will be okay, however, it's not okay;
0:49 here is what happens if you try to return a type that is some kind of built in,
0:53 so you can see right here in the error, we're returning a car instance,
0:57 car object at ox106 etc, it's some memory address
1:02 and it says this thing is not json serializable.
1:04 However, it is very common to have these types of objects, right,
1:08 if we're using sqlalchemy to get something from the database,
1:11 mongo engine to get something from mongo db
1:14 all sorts of reasons we might have our own custom objects
1:16 even things as simple as datetimes,
1:19 like datetimes ar not json serializable, what do you there, right,
1:22 you better hope you don't have a thing that has a date, that's really common.
1:25 So what we're going to talk about now is how do we configure the json,
1:29 the built in json renderer to make this error go away
1:33 and serialize everything perfectly.