This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

Create a Node.js function for an HTTP DELETE request for a Swagger API

2:45 Node.js lesson by

This lesson shows you how to delete a Todo item from Elasticsearch using the Todo ID from the URL parameters according to the specifications defined in your Swagger API docs.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

This lesson shows you how to delete a Todo item from Elasticsearch using the Todo ID from the URL parameters according to the specifications defined in your Swagger API docs.

In my Swagger specification under the /todo endpoint followed by the ID, I have a delete operation defined that will allow me to delete a specific to do by its ID.

It accepts a parameter of the ID number that's found in the URL path, which we can see right up here. It's this ID in the curly braces. The Swagger router controller looks for a file named delete to do by ID, and then the function itself is called delete to do by ID. Let's create that now.

In my editor under the controllers folder, I'm going to add a new file and, according to our specification, I need to name that file delete to do my ID.

I'm going to declare my client, which is going to just call the ES function within my helpers folder that has all of my parameters for connecting to elastic search. Next, I'm going to export the function itself so that it can be found by the application.

Now, we can create that function. It has request and response parameters. First thing we'll do is just write out that we're deleting the to do. Now, the ID of the parameter came in on the URL string, or it came in on the URL path.

We're going to find that under request.swagger.params.ID.value. We're going to call the delete method of client, specify our index of to do, and the type of index is also to do.

Then, we provide the ID number of the to do we want to delete. Again, that's under request.swagger.params.id.value. Provide a callback that has an error in response object. Then, I'm going to set my header, because we need the content type header set to application/json.

Then, we'll check for that error object. If it exists, it's because we have an error. We just want to send that error back down to the client. Otherwise, it was successful, so we'll just send whatever response we got back from elastic search back down to the client.

To test that out, there's a to do with the ID number six that we just got from the get endpoint. I'm going to use curl and pass the delete method to it. We'll delete that. Response we got back was a success of one.

Now, we can check to see if that exists again. We get back a 404 because it's not found, it's working.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?