What would be the route model for an API Rest in more complex operations?

9

I researched a little about the REST API model, but among many questions I had, I had one that is essentially important.

The staff always gave examples of model routes similar to 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.

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

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

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

    • Checks whether the user exists;
    • Checks if the recovery code generated by the application has already been generated before for another user, to avoid duplicate codes;
    • Registers the recovery code;
    • Obtain the email template for password recoveries;
    • Send the email.
    asked by anonymous 03.09.2017 / 02:16

    2 answers

    8

    Some REST patterns (none required):

    1 - Use of nouns instead of verbs:

    /users - OK
    /cars  - OK
    
    /getAllUsers   - NOK
    /createNewUser - NOK
    /getAllCars    - NOK
    

    2 - GET request does not change resource state:

    GET /users?activate=true - NOK
    

    3 - Paths in the plural:

    /users - OK
    /user  - NOK
    

    4 - Use of Sub-Resources for Relationship Identification:

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

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

    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 Sorting:

    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 the API

    /v1/users
    

    8 - Error handling reported with a HTTP Status and one 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"
        }
      ]
    }
    

    About the password recovery issue is more or less what you described. You can have an endpoint that receives the user's email and triggers other services, eg:

    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 needs of each application.

        
    14.09.2017 / 05:52
    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 might 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 Recipe Book

        
    15.09.2017 / 19:32