What would the route model look like for a Rest API in more complex operations?

Asked

Viewed 2,058 times

11

I did some research on the REST API model, but among the many questions I had, I have one that is essentially important.

People always gave examples of route models that looked like this:

https://api.dominio.com.br/account[/{id}]

GET -> obtem o(s) usuário(s)
POST -> insere um novo usuário
PUT -> atualiza o usuário
DELETE -> remove o usuário

So far it works very well, I have the option to handle all users or only one, but only through the ID.

  1. If I want to select by email or username? How should it be done?
  2. If I need to pass more advanced parameters to the query, such as a WHERE or an ORDER BY or even a LIMIT, how to do?

@Edit

If possible, I would also like to know the following: in somewhat less abstract operations such as sending a password recovery email, the necessary processes for this should be done in the client application (which would have to make several requests to the API) or create a route that when called performs all necessary operations and delivers a prompt response to the client application?

The operations to send a password recovery email, are more or less in the template below:

  • Checks if the user exists;
  • Checks if the recovery code generated by the application has already been generated before for another user, to avoid duplicate codes;
  • Logs the recovery code;
  • Get email template for password recoveries;
  • Send the e-mail.
  • It is not because you are using REST that you are required to use only the PATH, (address path), it is totally acceptable to use querystring ?foo=bar&baz=foobar, but of course REST is REST, a REST call will not make a number of different things, so a lot of things you will be able to hit on the own PATH. To sum up, you want multiple actions and these actions are surely well solved if divided into different Urls (I believe that Slim has a group of routes, which should help to organize)

  • I suggest you look at these two sites: - JSON API - REST API tutorial With a quick read you will have a good understanding.

2 answers

10


A little REST standards(no mandatory):

1 - Use of nouns instead of verbs:

/users - OK
/cars  - OK

/getAllUsers   - NOK
/createNewUser - NOK
/getAllCars    - NOK

2 - GET request does not change the status of the resource:

GET /users?activate=true - NOK

3 - Paths in plural:

/users - OK
/user  - NOK

4 - Use of Relationship Identification Sub-Resources:

GET /users/1234/addresses - Retorna a lista de endereços que o usuário id=1234 possui.

5 - Content-Type and Accept for the definition of Serialization/Deserialization :

curl -XPOST https://api.service.com/v1/users -H "Content-Type:application/json" -H "Accept:text/xml" -d '{"firstName": "John", "lastName": "Doe"}'

Resultado:
<root>
    <message>Usuario cadastrado com sucesso</message>
    <entity>
         <id>1234</id>
         <firstName>John</firstName>
         <lastName>Doe</lastName>
    </entity>
</root>

6 - Filters, Paging and Ordering:

GET /users?lastName=Doe&age=18
GET /users?sort=-createdAt,+updatedAt
GET /users?fields=id,firstName,lastName
GET /users?offset=1&limit=10

7 - Versioning of the API

/v1/users

8 - Error handling informed with a HTTP Status and a payload

curl -XPOST https://api.server.com/v1/users -d '{"firstName":'

resposta:
HttpStatus 400 (Bad Request)
{
  "message": "Invalid request body"
}

curl -XPOST https://api.server.com/v1/users -d '{"firstName": null }'

resposta:
HttpStatus 422 (Unprocessable Entity)
{
  "message": "Unable to create the account"
  "errors": [
    {
       "attribute": "firstName",
       "message": "firstName cannot be null"
    }
  ]
}

On the issue of password recovery is more or less what you described. You can have an endpoint that receives the user’s email and triggers other services, e.g.:

POST /passwords {"email": "[email protected]"}

1 - API: Valida o cadastro e dispara um evento de recuperação de senha 
2 - Listener do Evento: Registra uma solicitação na base, dispara um email e um SMS (two factor)

The flow varies according to the need of each application.

  • He put a huge answer and did not answer directly and clearly what was asked.

  • 5

    +1 by the REST API "Cheat sheet". About the above comment, the first question is answered in item 6, and the "@Edit" is at the end...

1

Responding using your example (password recovery via email), we can look at this topic, where it is said:

Tadeck (2012) - You can use Controllers as alternatives to perform more complex actions. In your case, they can look like this:

(action)           (verb)   (URI)                          (type)
create:            POST   - /emails                         - collection
retrieve:          GET    - /email/{id}                     - resource
update:            PUT    - /email/{id}                     - resource
delete:            DELETE - /email/{id}                     - resource
send immediately:  POST   - /email/{id}/sendImmediately     - controller
just send:         POST   - /email/{id}/send                - controller
do something else: POST   - /email/{id}/someOtherActionType - controller

If you know English, I recommend reading the "REST Cookbook"

Browser other questions tagged

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