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, we want to start writing to it. So let's go back to our Postman client, we switch to a post request
0:11 to the people endpoint and we want to add the app payload to our request so let's go to the body tab and switch to application Json.
0:19 Notice, as we switch to Json a new header has been added for us, so the content type with this request is going to be application Json.
0:30 Now, all we need to do is add our body, Let's add a simple document with just one field, first name, John.
0:44 When we hit send, what we get back from our API is an error. Method not allowed. This is actually expected because by default,
0:54 Eve APIs are read only, and this is done to protect your data of course. If you want to allow write operation on your database,
1:01 you have to explicitly opt in. So let's. see how it's done. Back to our client, we go and as you might imagine,
1:10 what we need to do is add a new keyword here, resource, methods. So which are the methods that are supported at every endpoint
1:21 or resource in Eve terms. This is a list and the default is just a simple string with a get command. If you want to add support for write operation,
1:32 we add post command, and if we want to support the deletion, we go with the delete command. So let's save these and restart our server.
1:47 So now we are going to support not only read operations, but also write operation and delete operation.
1:57 Let's go back to our client and try our request again. We're still getting an error but it has changed. Now we're getting an unprocessable entity.
2:09 Now, this means that the write operation has been attempted, but there was some kind of error, and if we inspect the payload,
2:19 we see that we are getting a new keyword, a new meta keyword, and it is issues, this is a document, and it contains the list of errors,
2:30 as we can see, the problem here is that the first name field is unknown, this is because, again, even if Mongo is a schemaless
2:39 and you can write anything to Mongo, that doesn't mean that you really want to allow any kind of document and field to be stored on your database.
2:49 Most of the time you want your documents to be validated, and you want them to match some kind of schema. This is the reason why Eve doesn't allow you
2:57 to write unknown fields to your database. We will see that there is an option to allow unknown documents, but by default, that's not possible.
3:06 What we need to do now is define a schema for our endpoint.