JSON vs Form POST

前端 未结 3 671
孤街浪徒
孤街浪徒 2020-12-28 13:25

We\'re having a bit of a discussion on the subject of posting data to a REST endpoint. Since the objects are quite complex, the easiest solution is to simply serialize them

相关标签:
3条回答
  • 2020-12-28 13:51

    You can use JSON as part of the request data as the OP had stated all three options work.

    The OP needs to support JSON input as it had to support contain complex structural content. However, think of it this way... are you making a request to do something or are you just sending what is basically document data and you just happen to use the POST operation as the equivalent of create new entry.

    That being the case, what you have is basically a resource endpoint with CRUDL semantics. Following up on that you're actually not limited to application/json but any type that the resource endpoint is supposed to handle.

    For non-resource endpoints

    I find that (specifically for JAX-RS) the application/x-www-urlencoded one is better.

    1. Consistency with OAuth 2.0 and OpenID Connect, they use application/x-www-urlencoded.
    2. Easier to annotate the individual fields using Swagger Annotations
    3. Swagger provides more defaults.
    4. Postman generates a nice form for you to fill out and makes things easier to test.

    Examples of non-resource endpoints:

    • Authentication
    • Authorization
    • Simple Search (though I would use GET on this one)
    • Non-simple search where there are many criteria
    • Sending a message/document (though I would also consider multipart/form-data so I can pass meta data along with the content, but JAX-RS does not have a standard for this one Jersey and RestEasy have their own implementations)
    0 讨论(0)
  • 2020-12-28 13:59

    I'd say that both methods will work well it's important that you stay consistent across your APIs. The option I would personally choose is simply sending the content as application/json.

    POST doesn't force you to use application/x-www-form-urlencoded - it's simply something that's used a lot because it's what webbrowsers use.

    0 讨论(0)
  • 2020-12-28 14:16

    There is nothing wrong about sending it directly as serialized JSON, for example google does this by default in it's volley library (which obviously is their recommended REST library for android).

    If fact, there are plenty of questions on SO about how not to use JSON, but rather perform "normal" POST requests with volley. Which is a bit counter intuitive for beginners, having to overwrite it's base class' getParams() method.

    But google having it's own REST library doing this by default, would be my indicator that it is OK.

    0 讨论(0)
提交回复
热议问题