Eve: Building RESTful APIs with MongoDB and Flask Transcripts
Chapter: Your first Eve service
Lecture: Enabling writes
0:00 Now that we're connected to an actual database,
0:02 we want to start writing to it.
0:04 So let's go back to our Postman client, we switch to a post request
0:10 to the people endpoint and we want to add the app payload to our request
0:14 so let's go to the body tab and switch to application Json.
0:18 Notice, as we switch to Json a new header has been added for us,
0:24 so the content type with this request
0:26 is going to be application Json.
0:29 Now, all we need to do is add our body,
0:31 Let's add a simple document with just one field, first name, John.
0:43 When we hit send, what we get back from our API is an error.
0:48 Method not allowed. This is actually expected because by default,
0:53 Eve APIs are read only, and this is done to protect your data of course.
0:58 If you want to allow write operation on your database,
1:00 you have to explicitly opt in.
1:03 So let's. see how it's done.
1:06 Back to our client, we go and as you might imagine,
1:09 what we need to do is add a new keyword here, resource, methods.
1:16 So which are the methods that are supported at every endpoint
1:20 or resource in Eve terms.
1:24 This is a list and the default is just
1:26 a simple string with a get command.
1:28 If you want to add support for write operation,
1:31 we add post command, and if we want to support the deletion,
1:37 we go with the delete command.
1:40 So let's save these and restart our server.
1:46 So now we are going to support not only read operations,
1:50 but also write operation and delete operation.
1:56 Let's go back to our client and try our request again.
2:02 We're still getting an error but it has changed.
2:05 Now we're getting an unprocessable entity.
2:08 Now, this means that the write operation has been attempted,
2:13 but there was some kind of error,
2:15 and if we inspect the payload,
2:18 we see that we are getting a new keyword, a new meta keyword,
2:22 and it is issues, this is a document,
2:26 and it contains the list of errors,
2:29 as we can see, the problem here is
2:31 that the first name field is unknown,
2:33 this is because, again, even if Mongo is a schemaless
2:38 and you can write anything to Mongo,
2:40 that doesn't mean that you really want to allow
2:43 any kind of document and field
2:45 to be stored on your database.
2:48 Most of the time you want your documents to be validated,
2:51 and you want them to match some kind of schema.
2:53 This is the reason why Eve doesn't allow you
2:56 to write unknown fields to your database.
2:59 We will see that there is an option to allow unknown documents,
3:02 but by default, that's not possible.
3:05 What we need to do now is define a schema for our endpoint.