Eve: Building RESTful APIs with MongoDB and Flask Transcripts
Chapter: Fine-tuning your REST service
Lecture: Client and server projections

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Projections are a powerful feature, they allow a client to dictate of all document fields which ones should be returned with the response.
0:12 In this request here we're asking for just the last name field let's send it over and we can see that all the documents still have
0:22 the meta fields because these are always included no matter the projection. We can also exclude fields,
0:28 for example, here I'm excluding the last name field I want all the fields but not last name
0:34 and as you can see, here we're getting first name, location, age, role, etc, but no last name. Projections are nice because they allow the client
0:45 to pick only the fields it really needs. Imagine if the people document had a picture if we don't need a picture, we can just exclude it
0:56 and we won't be forced to download it, how nice is that? You can, of course, disable projections you simply go to the code editor in your settings file
1:06 and set projection to false. This is global, and as you might expect by now you can go and switch it on at local level if you want to.
1:25 So now projections are disabled at all endpoints but people. Of course, we can also change the word used to query for a projection
1:42 let me save, relaunch, go back to Postman, and use fields instead. Got it. Now, so far we've have seen that the client can control projections
2:01 but we can actually predefine projections on server side. Let's see how we do that. Let's first clean up a little bit,
2:16 all right, we define server side projections at the endpoint level, let me paste an example here,
2:24 data source is dictionary and it allows the projection key do not confuse this projection key with root level projection boolean
2:34 which allows you to turn projection feature on and off. So here we're setting a projection server side every request sent to the people endpoint
2:45 will not include last name by default let's try this, save, relaunch as usual and let's ask for people without any client projection, same response.
3:04 No last name included with the response as you can see, clients can still alter the output if they wish but that the default is a different projection
3:24 it is a server projection, default server side projection can come in handy in several situations one is the picture we mentioned before,
3:33 you aren't letting the clients download it by default but they can still go and require it with a specific projection should they need it.
3:42 Also keep in mind that projections are a read-only thing they don't apply to write operation.
3:49 You still have a schema endpoint and clients can still write the world document or edit the world document as they please.


Talk Python's Mastodon Michael Kennedy's Mastodon