HTTP methods in practice

Asked

Viewed 2,767 times

9

I’ve seen the W3C documentation some questions here at Sopt:

However I found it very conceptual, I still have some doubts of use in practice, for example, if I have a simple system of users, I have basically 5 operations: insertion (POST), search (GET), change (PUT), deletion (DELETE) and authentication (authentication checks a user’s data and the search picks up the data of all users, without needing their access data). If I’m wrong please correct me

  1. Which method will I use for authentication?
  2. Considering that I have 5 actions and that, according to the answers of the questions mentioned, there are 9 "official" methods, when I will use the others?
  3. If I use the GET method to pick up something very important, and therefore the user data must be informed again (user and password), I must pass this by the url (examplo.com/given/user/password)?
  • Quick response: conceptually authentication is not part of the user resource. It would be better for you to separate responsibilities and create your own service, so you can use all the methods needed for authentication.

  • @Andersoncarloswoss did not understand this quick response, can explain better?

5 answers

7


With the large increase in the use of the HTTP protocol in API these methods came to the fore. In direct transactions you can use the method you want, but some have its restrictions, such as GET and DELETE, for example, you cannot have a body in the request. But some languages these restrictions can be hurt. The importance of different methods is a protocol for understanding the purpose of the request. And this will help in understanding the resources of your application. Let’s go to the protocol methods:

Standard methods of the HTTP protocol

  • GET: Information request method. This method is useful to fetch some information requested both by way http://meusite/api/usuarios or http://meusite/api/usuarios/235 by a filter http://meusite/api/usuarios?status=ativo. As the goal is to return some information, then this method should not wait for a body in the request. So the method will have a faster transaction in the request.
  • POST: Input method. It is an extremely useful method as it is a method that will perform an action. The method does not require a body either in the request or in the response. You should understand this method as you will have an execution on the server. Examples:

    1 - Insert values: Running a POST in http://meusite/api/users being in the body the values of the new user. This way we know that the body information will be inserted in the list of users.

    2 - Update values: As much as we have the method PUT, it is not considered protocol break to use the POST to do a data update. That is why the browser does not use the method PUT, because at the beginning of the HTTP protocol only methods existed GET and POST.

    3 - Perform some functionality: If there is some calculation execution or more specific functionality (not a query, because that’s the GET) uses the POST protocol for this execution. An example would be http://meusite/api/usuarios/parabenizar-aniversariantes. This does not mean that this feature has a body in both the request and the answer.

  • PUT: It is a specific method to update values. It would not be correct to use PUT for running functionality, as we saw in the POST. Then you will have as default a body in the request and the path will have, for security, the reference key of the data being updated http://meusite/api/usuarios/234. This way the protocol will refuse requests that come without a key.

  • PATCH: An aid method of the PUT is the PATCH. It also aims to update values of a key reference in the path http://meusite/api/usuarios/234, but the body will not have the complete object. So the values update are partial. An example is in the process of updating password, do not need to send the whole body for the password change. This way you will have better security and validation in case of password change and avoid including if in the PUT.

    • An example comparing the PUT and the PATCH we’ll have an object User in which it will have the following complete body:

      {
      "Id":"7e8f2ae6-a5b1-41e7-b9fd-2ae8863fa39d",
      "Nome":"Joãozinho",
      "Email":"[email protected]",
      "Login":"joaozinho",
      "DataNascimento":"01/01/1990"
      }
      

      To perform a complete data change you would use the PUT. So the request would be (I will not consider any Authorization protocol):

    Method: PUT

    Url: http://meusite/api/usuarios/7e8f2ae6-a5b1-41e7-b9fd-2ae8863fa39d

    Heard: ["Content-Type":"application/json"]

    Body:

    {
        "Id":"7e8f2ae6-a5b1-41e7-b9fd-2ae8863fa39d",
        "Nome":"Joãozinho Sauro",
        "Email":"[email protected]",
        "Login":"joaozinho",
        "DataNascimento":"01/01/1990"
    }
    

    Already the PATCH it would be an understanding that the process used in that method is for a specific change. As an example I will make a login change process, because we will understand that on the server side it will have a login validator available, for example. Then the requisition would be as follows:

    Method: PATCH

    Url: http://meusite/api/usuarios/7e8f2ae6-a5b1-41e7-b9fd-2ae8863fa39d/mudar-login

    Heard: ["Content-Type":"application/json"]

    Body:

    {
        "Login":"joaozinho30"
    }
    

    Like I said, protocol doesn’t require you to do it that way. It is useful for better understanding of every feature your service is offering. But if you want to do these two examples on POST you can. Where the difference include a new User and update data from User will be in the URL. Then this will be part of the architectural decision of the project in which pattern the team will follow. But if your project will be for public use, it will be very well accepted if the service faithfully adheres to the protocol.

  • DELETE: Although it is a new method for the beginnings of HTTP, but like the GET, is a method that should not pass a body. This way the process gains a higher speed in the requisition, since the goal is simply a cleaning. This way your process will have a better organization, because you will know that the exclusions will only be in the method DELETE.

  • OPTIONS: A major browser usage method. When you use the HTTPS protocol by default the browser will request which methods it can use with the current url. This way the process will return only the list of allowed methods run, for example POST, GET, PUT, DELETE.

  • HEAD: Not enough to improve the transaction time of the POST to the GET, the method HEAD will have an extra gain. Because the goal is the information that contains in HEAD response. This is very useful for updating Token, for example.

  • CONNECT: It is an HTTP protocol feature for you to open a direct connection tunnel. This is useful for extreme security process case that will open a kind of VNP for communication.

  • TRACE: A simple process to test communication. It is useful in case of a very time-consuming execution being processed by other methods and asynchronously the TRACE will be valid if there is still communication with the server or the delay is due to a communication breakdown.

William, so you can put the authentication in the method you want, but by default protocol and to facilitate maintenance for new team members is better use the method POST.

Well, I hope I’ve met your expectation. But it was great training to answer that question.

NOTE: There was an answer to this question in another post /a/9421/114084, so I added a little more to my understanding so that I can share my understanding.

  • The link you put is in the question and was one that I found very conceptual, I liked the answer as it explains what and shows a practical example, but I’m still doubtful about the PATCH could explain a little more? How I use it and what is the difference to the PUT?

  • made a question related to the body of requests, I believe you might be interested, or others who are searching about HTTP

  • William, I made an issue by putting an example between the PUT and the PATCH. See if it gets better.

  • As for the body issue, in the HTTP protocol the request you can do the way you want. No one can tell you that you cannot have body, or that the URL is wrong, or anything else. What happens is that in some languages (Java or .Net, for example) will not give you the body in case of use of the method GET. You can circumvent this, but it will be a very expensive programming cost rather than simply accepting normal protocol. It’s kind of boring the requirements of the protocol, but when it gets used it is even easier to work. rs

  • I understood better, but in the example there was one last question (I hope), if I want, when a user is registering or changing the username field, to make a call to the api according to what he types to check if that user is available. This call is GET or PATCH or other?

  • The login query available, as example, for being a consultation the method should be the GET. The accessed login would be informed by Query String (parameter in the URL). Because what you are doing is only a query in the database. Now, if a query requires a server-side execution of a calculation or data change, then that would be a concept for the POST. Feel free to doubt!!

Show 1 more comment

5

TL;DR: not that there needs to be a resource for authentication, but it needs authorization for you to manipulate a resource.


The first concept to be understood from REST is the recourse. It is something to be downloaded on the web.

Metaphorically, think of a library. It has many resources: books, people, employees.

GET

It’s very simple to think of REST that way. If I want to know about a book, I can do:

GET api.biblioteca.com/livros/iliada

{
  "autor": "Homero",
  "título": "Ilíada",
  "descrição": "A Ilíada (em grego antigo: Ἰλιάς, IPA: [iːliás]) é um dos dois principais poemas épicos da Grécia Antiga, de autoria atribuída ao poeta Homero, que narra os acontecimentos decorridos no período de 50 dias durante o décimo e último ano da Guerra de Troia, conflito empreendido para a conquista de Ílion ou Troia, cuja gênese radica na ira (μῆνις, mênis) de Aquiles."
}

If I want all of Homer’s books, I’ll make it look like query string:

GET api.biblioteca.com/livros?autor=Homero

[ { ... }, { ...} ]

Or depending on the design of your API, it could also be: api.biblioteca.com/autor/homero/livros

It can be concluded that the HTTP GET method, in REST, is using to return one or more resources.

DELETE

If you need to take a book from the library, just use DELETE.

DELETE api.biblioteca.com/livros/iliada

POST

This method sends data to the server. In REST, we use it to create a new resource.

Because it’s not idempotent, you can’t cache the response to a request like this.

POST api.biblioteca.com/livros

{
  "autor": "William Shakespeare",
  "título": "Macbeth",
  "descrição": "Macbeth é uma tragédia do dramaturgo inglês William Shakespeare, sobre um regicídio e suas consequências. É a tragédia shakespeariana mais curta, e acredita-se que tenha sido escrita entre 1603 e 1607. O primeiro relato de uma performance da peça é de abril de 1611, quando Simon Forman registrou tê-la visto no Globe Theatre, em Londres. A obra foi publicada pela primeira vez no Folio, de 1623, possivelmente a partir de uma transcrição de alguma performance específica."
}

PUT

Like the POST, it is used to send data to the server. In REST, it is used to update unique resources, such as a specific book.

Because it is ideal, the response of the requests can be cached.

PUT api.biblioteca.com/livros/arte-da-guerra

{
  "autor": "Sun Tzu",
  "título": "Arte da Guerra"
}

PATCH

Like PUT, it is used to send data to the server. In REST, it is used to update partial resources. Such as adding or updating a single field in an entity.

It may or may not be idempotent, so it may be a somewhat confusing method.

PATCH api.biblioteca.com/livros/arte-da-guerra

{
  "descrição": "A Arte da Guerra (chinês: 孫子兵法; pinyin: sūn zĭ bīng fǎ, literalmente "Estratégia Militar de Sun Tzu"), é um tratado militar escrito durante o século IV a.C. pelo estrategista conhecido como Sun Tzu. O tratado é composto por treze capítulos, cada qual abordando um aspecto da estratégia de guerra, de modo a compor um panorama de todos os eventos e estratégias que devem ser abordados em um combate racional. Acredita-se que o livro tenha sido usado por diversos estrategistas militares através da história como Napoleão, Zhuge Liang, Cao Cao, Takeda Shingen, Vo Nguyen Giap e Mao Tse Tung."
}

POST vs PUT vs PATCH

There are numerous discussions comparing the two methods and their use. It is important to note that REST is only a standard, and does not solve all cases.

  • Use POST to create new features in collection endpoints, such as api.biblioteca.com/livros.
  • Use PUT to update resources in entity endpoints, such as api.biblioteca.com/livros/iliada.
  • Use PATCH to partially update resources, also in entity endpoints.

In short...

+-----------------------------+-----+------+-----+-------+--------+
|                             | GET | POST | PUT | PATCH | DELETE |
+-----------------------------+-----+------+-----+-------+--------+
| Requisição aceita body?     | Não | Sim  | Sim | Sim   | Sim    |
| Resposta aceita body?       | Sim | Sim  | Sim | Sim   | Sim    |
| Altera estado dos recursos? | Não | Sim  | Sim | Sim   | Sim    |
| É idempotente?              | Sim | Não  | Sim | Não   | Sim    |
| É cacheável?                | Sim | Não* | Não | Não   | Não    |
+-----------------------------+-----+------+-----+-------+--------+

* depende do que vier nos headers

Okay, but what about authentication?

As I said, REST does not solve everything, nor should it. Not everything is resource or can be represented as one. There goes from implementation to implementation.

There are several ways to authenticate using HTTP, and the vast majority have nothing to do with the HTTP method, but sessions, cookies or HTTP headers.

The point is: it’s not that there needs to be a resource for authentication, but it needs authorization for you to delete a book, for example.

Basic authentication with HTTP

The golden tip, first, is to be using HTTPS. At each request made, an HTTP header indicating an authentication token.

DELETE api.biblioteca.com/livros/arte-da-guerra 
Authorization: Basic QWxhZGRpxjpvcGVuIHNlc2FtZS==

I recommend reading more about this authentication method on MDN.

  • 1

    Your answer became reference for REST, I’ll put it in the mandatory readings from here company.

  • Glad to hear it, @Jeffersonquesado!

2

Which method will I use for authentication?

To answer what I said and was not addressed in the other answers.

Resource of user is different from resource authentication. Imagine that you have the user resource under the URI /user, then:

  • GET /user search user information;
  • POST /user creates a new user;
  • PUT /user updates/creates user data;
  • DELETE /user deletes a user;
  • PATCH /user updates a user;

How do you authenticate a user? With another feature, for example, /auth.

  • GET /auth search information of an authentication;
  • POST /auth creates a new authentication;
  • etc.;

If you want to authenticate a registered user, just make a POST for the authentication resource. Normally this request will generate a token which identifies which user authentication is, and usually this token is stored in cookies customer’s.

Considering that I have 5 actions and that, according to the answers of the questions mentioned, there are 9 "official" methods, when I will use the others?

The other answers address this issue.

If I use the method GET to pick up something very important, and therefore user data must be informed again (user and password), I must pass this through the URL (exemplo.com/dado/usuario/senha)?

No, user data for authentication must be passed exclusively for the authentication resource. Having to pass this on to another resource would be redundancy and harm the atomicity of its resources. If another resource needs authentication to access it, you should pass only the token authentication, through the request headers, and validate it on the server side. The response of the vnbrs exemplifies very well this in the part that speaks of authentication.

  • This is not the case, but it would be semantically incorrect to use user|client|worker/auth, if for example I have authentication of users, employees and customers and each one has a different form?

  • No, perfectly acceptable. The URI is opaque, it does not reflect any logic implemented on the server, so just by owning user on the way does not necessarily mean that it belongs to the user resource.

2

Hello,

I’ll try to get to the point, answering only your questions.

Which method will I use for authentication?

The method is usually used POST. Certainly authentication is a concept that does not seem to fit very well in any HTTP method, but usually we adopt the POST in these cases :)

Considering that I have 5 actions and that, according to the answers of the questions mentioned, there are 9 "official" methods, when I will use the others?

Unfortunately you will not always be able to find an HTTP method suitable for all the actions you want to do on the system. Even, be careful when using some of the rarest HTTP methods, as you may have problems unexpected with firewall among other environmental surprises.

Usually people stick to the classics: GET, POST, PUT, DELETE and (rarer) PATCH. The PATCH is used when the user wants to update only information specific to the HTTP entity and does not want to send all information to each update, as is done in PUT.

If I use the GET method to pick up something very important, and therefore the user data must be informed again (user and password), I must pass this by the url (examplo.com/given/user/password)?

Passing the user and password through the URL is something that never should be done. If certain endpoint of consultation need user and password, this information must be passed in the body of the message (body). Like the GET does not accept a body (or should not accept.. ), it is used POST same. Example:

POST /api/consultar-dado-importante/123

Body: 
{
    "usuario": "user", "senha": "123456"
}

Use POST instead of GET in these cases is an exception the rule.

Plus, here’s my tip: you won’t find a ready answer on how to use the correct HTTP method or code for each issue in your project. Just try to choose a pattern in your API and follow it all the time by creating an internal standard.

If you have any more questions or something that is not clear, use the comment area that I can clarify some points.

-7

usually has yes, always various operations you can do in this case.

But the most used ones are GET and POST as you may have read, probably already have knowledge of what each one does:

GET = FASTER, BUT LESS SAFE.

POST = Slower, but safer.

ie use get to pass some information that is not relevant to the server through the url. and use the post to pass some information such as password, or credit card number, something that is more confidential Voce can not leave visible by the url.

I believe you now understand better which one to use.

  • Your answer is a little vague and only answers what you haven’t asked (GET vs POST), add more data, for example, because it’s more or less fast and safe? (I’m sorry if I seem ungrateful is not the intention :) )

  • 2

    I was also curious about these statements. Why do you say one is faster than another and why is one safer? Both send the information via text, so what would be the difference in security?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.