HTTP / LESSON 04

HTTP methods

Create, read, update, and delete a contact using different methods.

The method says what you want to do, and the URL says what you want to do it to. In this lesson, you'll take a contact through its whole life.

Everyone in the class is using the same API. To avoid getting in each other's way, change only the contacts that you create.

GET: read

GET reads a resource. It's the default for curl and the explorer.

Request headers 0

POST: create

POST sends data to the server. Here, it creates a new contact in the list. Put your own name in the body before you send it.

Request headers 1

Look at three things in the response:

  • The status is 201 Created, not 200 OK.
  • The body includes the new contact's id. The server chose it.
  • The location header gives the URL of the new contact.

Note your contact's id. The examples below use 128. Replace it with your own id each time.

GET the new contact

Use the location from the previous response.

PUT: replace

PUT replaces a resource with what you send. This API requires both name and mobile.

-d makes curl use POST by default, so -X PUT sets the method.

Experiment: Send the PUT with only a name. It's a replacement, so a missing mobile is an error. Some APIs offer PATCH, which changes only the fields you send. This one doesn't.

DELETE: delete

The status is 204 No Content. It worked, and there's nothing to return.

Your turn: Now GET the same URL again. What status do you get?

A URL supports only some methods

Try to delete the whole list:

The server refuses with 405 Method Not Allowed. The allow header lists the methods this URL does support.

You can ask for that list directly with OPTIONS:

Your turn: Compare the methods allowed on /api/contacts and /api/contacts/123. Why is POST on one and PUT on the other?

The methods at a glance

Method Meaning On this API
GET Read a resource GET /api/contacts/123
HEAD Same as GET, but only the headers HEAD /api/contacts/123
POST Submit data: typically, create something new POST /api/contacts
PUT Replace a resource PUT /api/contacts/123
PATCH Change part of a resource Not supported
DELETE Delete a resource DELETE /api/contacts/123
OPTIONS Ask what this URL supports OPTIONS /api/contacts/123

Notice how few URLs this API has. It has two, and the methods do the rest.

Summary

  • The method says what to do, and the URL says what to do it to.
  • POST creates, GET reads, PUT replaces, and DELETE deletes.
  • Each URL supports its own set of methods, listed in Allow.

Next, we'll see what happens when you send the same request twice.