All topics

REST APIs interview questions

85 questions, 74 with answers. 2,830 open jobs in India ask for REST APIs.

  1. What is rest architecture? What are the requirements?
    • resources being identified by a persistent identifier: URIs are the ubiquitous choice of identifier these days
    • resources being manipulated using a common set of verbs: HTTP methods are the commonly seen case - the venerable Create, Retrieve, Update, Delete becomes POST, GET, PUT, and DELETE. But REST is not limited to HTTP, it is just the most commonly used transport right now.
    • the actual representation retrieved for a resource is dependent on the request and not the identifier: use Accept headers to control whether you want XML, HTTP, or even a Java Object representing the resource
    • maintaining the state in the object and representing the state in the representation
    • representing the relationships between resources in the representation of the resource: the links between objects are embedded directly in the representation
    • resource representations describe how the representation can be used and under what circumstances it should be discarded/refetched in a consistent manner: usage of HTTP Cache-Control headers Links
    • https://stackoverflow.com/questions/671118/what-exactly-is-restful-programming
    • https://restfulapi.net/rest-architectural-constraints/

    From Java interview (MIT)

  2. Is there state in rest architecture?

    As per the REST (REpresentational “State” Transfer) architecture, the server does not store any state about the client session on the server side. This restriction is called Statelessness. Each request from the client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client. client is responsible for storing and handling all application state related information on client side. Links

    • https://restfulapi.net/statelessness/

    From Java interview (MIT)

  3. Can be used query params in rest architecture?

    I'd recommend putting any required parameters in the path, and any optional parameters should certainly be query string parameters. Putting optional parameters in the path will end up getting really messy when trying to write URL handlers that match different combinations. Links

    • https://stackoverflow.com/questions/4024271/rest-api-best-practices-where-to-put-parameters
    • https://stackoverflow.com/questions/11552248/when-to-use-queryparam-vs-pathparam

    From Java interview (MIT)

  4. What is the difference get and post?
    • GET is idempotent: it is for obtaining a resource, without changing anything on the server. As a consequence it should be perfectly safe to resubmit a GET request.
    • POST is not: it is for updating information on the server. It can therefore not be assumed that it is safe to re-submit the request which is why most browsers ask for confirmation when you hit refresh on a POST request. Links
    • https://stackoverflow.com/questions/2080863/what-is-the-difference-between-a-http-get-and-http-post-and-why-is-http-post-wea

    From Java interview (MIT)

  5. What is the difference between soap and rest?
    • REST API has no has no official standard at all because it is an architectural style. SOAP API, on the other hand, has an official standard because it is a protocol.
    • REST APIs uses multiple standards like HTTP, JSON, URL, and XML while SOAP APIs is largely based on HTTP and XML.
    • As REST API deploys multiple standards, so it takes fewer resources and bandwidth as compared to SOAP that uses XML for the creation of Payload and results in the large sized file.
    • The ways both APIs exposes the business logics are also different. REST API takes advantage of URL exposure like @path("/WeatherService") while SOAP API use of services interfaces like @WebService.
    • SOAP API defines too many standards, and its implementer implements the things in a standard way only. In the case of miscommunication from service, the result will be the error. REST API, on the other hand, don't make emphasis on too many standards and results in corrupt API in the end.
    • REST API uses Web Application Description Language, and SOAP API used Web Services Description language for describing the functionalities being offered by web services.
    • REST APIs are more convenient with JavaScript and can be implemented easily as well. SOAP APIs are also convenient with JavaScript but don't support for greater implementation. Links
    • https://dzone.com/articles/difference-between-rest-and-soap-api

    From Java interview (MIT)

  6. Is it correct to update something during get request?

    no. GET is idempotent: it is for obtaining a resource, without changing anything on the server. As a consequence it should be perfectly safe to resubmit a GET request. Links

    • https://stackoverflow.com/questions/2080863/what-is-the-difference-between-a-http-get-and-http-post-and-why-is-http-post-wea

    From Java interview (MIT)

  7. Is it possible to use body in get requests?

    Yes, you can send a request body with GET but it should not have any meaning. If you give it meaning by parsing it on the server and changing your response based on its contents, then you are ignoring this recommendation in the HTTP/1.1 spec, section 4.3:

    [...] if the request method does not include defined semantics for an entity-body, then the message-body SHOULD be ignored when handling the request. Links

    • https://stackoverflow.com/questions/978061/http-get-with-request-body

    From Java interview (MIT)

  8. What are possible types of requests for http protocol?

    GET

    The GET method requests a representation of the specified resource. Requests using GET should only retrieve data.

    HEAD

    The HEAD method asks for a response identical to that of a GET request, but without the response body.

    POST

    The POST method is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.

    PUT

    The PUT method replaces all current representations of the target resource with the request payload.

    DELETE

    The DELETE method deletes the specified resource.

    CONNECT

    The CONNECT method establishes a tunnel to the server identified by the target resource.

    OPTIONS

    The OPTIONS method is used to describe the communication options for the target resource.

    TRACE

    The TRACE method performs a message loop-back test along the path to the target resource.

    PATCH

    The PATCH method is used to apply partial modifications to a resource. Links

    • https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods

    From Java interview (MIT)

  9. Why method options is needed?

    The HTTP OPTIONS method is used to request information about the communication options available for the target resource. The response may include an Allow header indicating allowed HTTP methods on the resource, or various Cross Origin Resource Sharing headers. The HTTP OPTIONS method is both safe and idempotent, as it is intended only for use in querying information about ways to interact with a resource. Links

    • https://egghead.io/lessons/tools-use-http-options-method

    From Java interview (MIT)

  10. What is the difference between put and post?
    • POST to a URL creates a child resource at a server defined URL.
    • PUT to a URL creates/replaces the resource in its entirety at the client defined URL.
    • PATCH to a URL updates part of the resource at that client defined URL. Links
    • https://stackoverflow.com/questions/630453/put-vs-post-in-rest

    From Java interview (MIT)

  11. What can be used as rest client?
    1. Netflix provides Feign as an abstraction over REST-based calls, by which microservices can communicate with each other, but developers don't have to bother about REST internal details.
    2. Jersey
    3. Spring RestTemplate Links
    • https://dzone.com/articles/microservices-communication-feign-as-rest-client
    • https://stackoverflow.com/questions/221442/rest-clients-for-java

    From Java interview (MIT)

  12. How http protocol work?

    As a request-response protocol, HTTP gives users a way to interact with web resources such as HTML files by transmitting hypertext messages between clients and servers. HTTP clients generally use Transmission Control Protocol (TCP) connections to communicate with servers. Links

    • https://www.extrahop.com/resources/protocols/http/
    • https://www.quora.com/How-does-HTTP-work

    From Java interview (MIT)

  13. What are the possible solutions in the case of big number of parameters for search method?
    1. POST request with body;
    2. Encoding the query string in GET request;
    3. Aliases. Links
    • https://softwareengineering.stackexchange.com/questions/353086/what-is-a-proper-way-to-do-a-complex-restful-search-method

    From Java interview (MIT)

  14. What should be the response in the case of DELETE request?

    There is no hard RESTful standard. 204 No Content is a popular response for DELETE. Links

    • https://stackoverflow.com/questions/25970523/restful-what-should-a-delete-response-body-contain

    From Java interview (MIT)

  15. Is it good practice to use Map<String, Object> in a model for a REST API?

    Using Map<String, Object> in REST models is generally discouraged due to poor type safety, lack of schema clarity, and harder API validation. However, it can be acceptable for internal use, plugin-like extensibility, or storing custom metadata.

    Home Page

    From Java interview (MIT)

  16. What is the difference between POST and PUT in HTTP?

    Overall:

    Both PUT and POST can be used for creating.

    You have to ask, "what are you performing the action upon?", to distinguish what you should be using. Let's assume you're designing an API for asking questions. If you want to use POST, then you would do that to a list of questions. If you want to use PUT, then you would do that to a particular question.

    Great, both can be used, so which one should I use in my RESTful design:

    You do not need to support both PUT and POST.

    Which you use is up to you. But just remember to use the right one depending on what object you are referencing in the request.

    Some considerations:

    • Do you name the URL objects you create explicitly, or let the server decide? If you name them then use PUT. If you let the server decide then use POST.
    • PUT is defined to assume idempotency, so if you PUT an object twice, it should have no additional effect. This is a nice property, so I would use PUT when possible. Just make sure that the PUT-idempotency actually is implemented correctly in the server.
    • You can update or create a resource with PUT with the same object URL
    • With POST you can have 2 requests coming in at the same time making modifications to a URL, and they may update different parts of the object.

    An example:

    I wrote the following as part of another answer on SO regarding this:

    POST:

    Used to modify and update a resource

    POST /questions/<existing_question> HTTP/1.1
    Host: www.example.com/
    

    Note that the following is an error:

    POST /questions/<new_question> HTTP/1.1
    Host: www.example.com/
    

    If the URL is not yet created, you should not be using POST to create it while specifying the name. This should result in a 'resource not found' error because <new_question> does not exist yet. You should PUT the <new_question> resource on the server first.

    You could though do something like this to create a resources using POST:

    POST /questions HTTP/1.1
    Host: www.example.com/
    

    Note that in this case the resource name is not specified, the new objects URL path would be returned to you.

    PUT:

    Used to create a resource, or overwrite it. While you specify the resources new URL.

    For a new resource:

    PUT /questions/<new_question> HTTP/1.1
    Host: www.example.com/
    

    To overwrite an existing resource:

    PUT /questions/<existing_question> HTTP/1.1
    Host: www.example.com/
    

    Additionally, and a bit more concisely, RFC 7231 Section 4.3.4 PUT states (emphasis added),

    4.3.4. PUT

    The PUT method requests that the state of the target resource be created or replaced with the state defined by the representation enclosed in the request message payload.

    From Stack Overflow: asked by alex, answered by Brian R. Bondy (CC BY-SA 4.0)

  17. What exactly is RESTful programming?

    REST is the underlying architectural principle of the web. The amazing thing about the web is the fact that clients (browsers) and servers can interact in complex ways without the client knowing anything beforehand about the server and the resources it hosts. The key constraint is that the server and client must both agree on the media used, which in the case of the web is HTML.

    An API that adheres to the principles of REST does not require the client to know anything about the structure of the API. Rather, the server needs to provide whatever information the client needs to interact with the service. An HTML form is an example of this: The server specifies the location of the resource and the required fields. The browser doesn't know in advance where to submit the information, and it doesn't know in advance what information to submit. Both forms of information are entirely supplied by the server. (This principle is called HATEOAS: Hypermedia As The Engine Of Application State.)

    So, how does this apply to HTTP, and how can it be implemented in practice? HTTP is oriented around verbs and resources. The two verbs in mainstream usage are GET and POST, which I think everyone will recognize. However, the HTTP standard defines several others such as PUT and DELETE. These verbs are then applied to resources, according to the instructions provided by the server.

    For example, Let's imagine that we have a user database that is managed by a web service. Our service uses a custom hypermedia based on JSON, for which we assign the mimetype application/json+userdb (There might also be an application/xml+userdb and application/whatever+userdb - many media types may be supported). The client and the server have both been programmed to understand this format, but they don't know anything about each other. As Roy Fielding points out:

    A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types.

    A request for the base resource / might return something like this:

    Request

    GET /
    Accept: application/json+userdb
    

    Response

    200 OK
    Content-Type: application/json+userdb
    {
        "version": "1.0",
        "links": [
            {
                "href": "/user",
                "rel": "list",
                "method": "GET"
            },
            {
                "href": "/user",
                "rel": "create",
                "method": "POST"
            }
        ]
    }
    

    We know from the description of our media that we can find information about related resources from sections called "links". This is called Hypermedia controls. In this case, we can tell from such a section that we can find a user list by making another request for /user:

    Request

    GET /user
    Accept: application/json+userdb
    

    Response

    Read the rest at the sourceFrom Stack Overflow: asked by hasen, answered by Emil H (CC BY-SA 4.0)

  18. SOAP vs REST (differences)

    Unfortunately, there are a lot of misinformation and misconceptions around REST. Not only your question and the answer by @cmd reflect those, but most of the questions and answers related to the subject on Stack Overflow.

    SOAP and REST can't be compared directly, since the first is a protocol (or at least tries to be) and the second is an architectural style. This is probably one of the sources of confusion around it, since people tend to call REST any HTTP API that isn't SOAP.

    Pushing things a little and trying to establish a comparison, the main difference between SOAP and REST is the degree of coupling between client and server implementations. A SOAP client works like a custom desktop application, tightly coupled to the server. There's a rigid contract between client and server, and everything is expected to break if either side changes anything. You need constant updates following any change, but it's easier to ascertain if the contract is being followed.

    A REST client is more like a browser. It's a generic client that knows how to use a protocol and standardized methods, and an application has to fit inside that. You don't violate the protocol standards by creating extra methods, you leverage on the standard methods and create the actions with them on your media type. If done right, there's less coupling, and changes can be dealt with more gracefully. A client is supposed to enter a REST service with zero knowledge of the API, except for the entry point and the media type. In SOAP, the client needs previous knowledge on everything it will be using, or it won't even begin the interaction. Additionally, a REST client can be extended by code-on-demand supplied by the server itself, the classical example being JavaScript code used to drive the interaction with another service on the client-side.

    I think these are the crucial points to understand what REST is about, and how it differs from SOAP:

    • REST is protocol independent. It's not coupled to HTTP. Pretty much like you can follow an ftp link on a website, a REST application can use any protocol for which there is a standardized URI scheme.

    • REST is not a mapping of CRUD to HTTP methods. Read this answer for a detailed explanation on that.

    • REST is as standardized as the parts you're using. Security and authentication in HTTP are standardized, so that's what you use when doing REST over HTTP.

    • REST is not REST without hypermedia and HATEOAS. This means that a client only knows the entry point URI and the resources are supposed to return links the client should follow. Those fancy documentation generators that give URI patterns for everything you can do in a REST API miss the point completely. They are not only documenting something that's supposed to be following the standard, but when you do that, you're coupling the client to one particular moment in the evolution of the API, and any changes on the API have to be documented and applied, or it will break.

    • REST is the architectural style of the web itself. When you enter Stack Overflow, you know what a User, a Question and an Answer are, you know the media types, and the website provides you with the links to them. A REST API has to do the same. If we designed the web the way people think REST should be done, instead of having a home page with links to Questions and Answers, we'd have a static documentation explaining that in order to view a question, you have to take the URI stackoverflow.com/questions/<id>, replace id with the Question.id and paste that on your browser. That's nonsense, but that's what many people think REST is.

    Read the rest at the sourceFrom Stack Overflow: asked by Abdulaziz, answered by Pedro Werneck (CC BY-SA 3.0)

  19. Use of PUT vs PATCH methods in REST API real life scenarios

    NOTE: When I first spent time reading about REST, idempotence was a confusing concept to try to get right. I still didn't get it quite right in my original answer, as further comments (and Jason Hoetger's answer) have shown. For a while, I have resisted updating this answer extensively, to avoid effectively plagiarizing Jason, but I'm editing it now because, well, I was asked to (in the comments).

    After reading my answer, I suggest you also read Jason Hoetger's excellent answer to this question, and I will try to make my answer better without simply stealing from Jason.

    Why is PUT idempotent?

    As you noted in your RFC 2616 citation, PUT is considered idempotent. When you PUT a resource, these two assumptions are in play:

    1. You are referring to an entity, not to a collection.

    2. The entity you are supplying is complete (the entire entity).

    Let's look at one of your examples.

    { "username": "skwee357", "email": "skwee357@domain.example" }
    

    If you POST this document to /users, as you suggest, then you might get back an entity such as

    ## /users/1
    {
        "username": "skwee357",
        "email": "skwee357@domain.example"
    }
    

    If you want to modify this entity later, you choose between PUT and PATCH. A PUT might look like this:

    PUT /users/1
    {
        "username": "skwee357",
        "email": "skwee357@gmail.com"       // new email address
    }
    

    You can accomplish the same using PATCH. That might look like this:

    PATCH /users/1
    {
        "email": "skwee357@gmail.com"       // new email address
    }
    

    You'll notice a difference right away between these two. The PUT included all of the parameters on this user, but PATCH only included the one that was being modified (email).

    When using PUT, it is assumed that you are sending the complete entity, and that complete entity replaces any existing entity at that URI. In the above example, the PUT and PATCH accomplish the same goal: they both change this user's email address. But PUT handles it by replacing the entire entity, while PATCH only updates the fields that were supplied, leaving the others alone.

    Since PUT requests include the entire entity, if you issue the same request repeatedly, it should always have the same outcome (the data you sent is now the entire data of the entity). Therefore PUT is idempotent.

    Using PUT wrong

    What happens if you use the above PATCH data in a PUT request?

    GET /users/1
    {
        "username": "skwee357",
        "email": "skwee357@domain.example"
    }
    PUT /users/1
    {
        "email": "skwee357@gmail.com"       // new email address
    }
    GET /users/1
    {
        "email": "skwee357@gmail.com"      // new email address... and nothing else!
    }
    

    (I'm assuming for the purposes of this question that the server doesn't have any specific required fields, and would allow this to happen... that may not be the case in reality.)

    Since we used PUT, but only supplied email, now that's the only thing in this entity. This has resulted in data loss.

    This example is here for illustrative purposes -- don't ever actually do this (unless your intent is to drop the omitted fields, of course... then you are using PUT as it should be used). This PUT request is technically idempotent, but that doesn't mean it isn't a terrible, broken idea.

    How can PATCH be idempotent?

    In the above example, PATCH was idempotent. You made a change, but if you made the same change again and again, it would always give back the same result: you changed the email address to the new value.

    Read the rest at the sourceFrom Stack Overflow: asked by Dmitry Kudryavtsev, answered by Dan Lowe (CC BY-SA 4.0)

  20. Is an entity body allowed for an HTTP DELETE request?

    The spec does not explicitly forbid or discourage it, so I would tend to say it is allowed.

    Microsoft sees it the same way (I can hear murmuring in the audience), they state in the MSDN article about the DELETE Method of ADO.NET Data Services Framework:

    If a DELETE request includes an entity body, the body is ignored [...]

    Additionally here is what RFC2616 (HTTP 1.1) has to say in regard to requests:

    • an entity-body is only present when a message-body is present (section 7.2)
    • the presence of a message-body is signaled by the inclusion of a Content-Length or Transfer-Encoding header (section 4.3)
    • a message-body must not be included when the specification of the request method does not allow sending an entity-body (section 4.3)
    • an entity-body is explicitly forbidden in TRACE requests only, all other request types are unrestricted (section 9, and 9.8 specifically)

    For responses, this has been defined:

    • whether a message-body is included depends on both request method and response status (section 4.3)
    • a message-body is explicitly forbidden in responses to HEAD requests (section 9, and 9.4 specifically)
    • a message-body is explicitly forbidden in 1xx (informational), 204 (no content), and 304 (not modified) responses (section 4.3)
    • all other responses include a message-body, though it may be of zero length (section 4.3)

    Update

    And in RFC 9110 (June 2022), The fact that request bodies on GET, HEAD, and DELETE are not interoperable has been clarified.

    section 9.3.5 Delete

    Although request message framing is independent of the method used, content received in a DELETE request has no generally defined semantics, cannot alter the meaning or target of the request, and might lead some implementations to reject the request and close the connection because of its potential as a request smuggling attack (Section 11.2 of [HTTP/1.1]). A client SHOULD NOT generate content in a DELETE request unless it is made directly to an origin server that has previously indicated, in or out of band, that such a request has a purpose and will be adequately supported. An origin server SHOULD NOT rely on private agreements to receive content, since participants in HTTP communication are often unaware of intermediaries along the request chain.

    From Stack Overflow: asked by Haacked, answered by Tomalak (CC BY-SA 4.0)

  21. Best practices for API versioning?

    This is a good and a tricky question. The topic of URI design is at the same time the most prominent part of a REST API and, therefore, a potentially long-term commitment towards the users of that API.

    Since evolution of an application and, to a lesser extent, its API is a fact of life and that it's even similar to the evolution of a seemingly complex product like a programming language, the URI design should have less natural constraints and it should be preserved over time. The longer the application's and API's lifespan, the greater the commitment to the users of the application and API.

    On the other hand, another fact of life is that it is hard to foresee all the resources and their aspects that would be consumed through the API. Luckily, it is not necessary to design the entire API which will be used until Apocalypse. It is sufficient to correctly define all the resource end-points and the addressing scheme of every resource and resource instance.

    Over time you may need to add new resources and new attributes to each particular resource, but the method that API users follow to access a particular resources should not change once a resource addressing scheme becomes public and therefore final.

    This method applies to HTTP verb semantics (e.g. PUT should always update/replace) and HTTP status codes that are supported in earlier API versions (they should continue to work so that API clients that have worked without human intervention should be able to continue to work like that).

    Furthermore, since embedding of API version into the URI would disrupt the concept of hypermedia as the engine of application state (stated in Roy T. Fieldings PhD dissertation) by having a resource address/URI that would change over time, I would conclude that API versions should not be kept in resource URIs for a long time meaning that resource URIs that API users can depend on should be permalinks.

    Sure, it is possible to embed API version in base URI but only for reasonable and restricted uses like debugging a API client that works with the the new API version. Such versioned APIs should be time-limited and available to limited groups of API users (like during closed betas) only. Otherwise, you commit yourself where you shouldn't.

    A couple of thoughts regarding maintenance of API versions that have expiration date on them. All programming platforms/languages commonly used to implement web services (Java, .NET, PHP, Perl, Rails, etc.) allow easy binding of web service end-point(s) to a base URI. This way it's easy to gather and keep a collection of files/classes/methods separate across different API versions.

    From the API users POV, it's also easier to work with and bind to a particular API version when it's this obvious but only for limited time, i.e. during development.

    From the API maintainer's POV, it's easier to maintain different API versions in parallel by using source control systems that predominantly work on files as the smallest unit of (source code) versioning.

    However, with API versions clearly visible in URI there's a caveat: one might also object this approach since API history becomes visible/aparent in the URI design and therefore is prone to changes over time which goes against the guidelines of REST. I agree!

    The way to go around this reasonable objection, is to implement the latest API version under versionless API base URI. In this case, API client developers can choose to either:

    • develop against the latest one (committing themselves to maintain the application protecting it from eventual API changes that might break their badly designed API client).

    • bind to a specific version of the API (which becomes apparent) but only for a limited time

    For example, if API v3.0 is the latest API version, the following two should be aliases (i.e. behave identically to all API requests):

    Read the rest at the sourceFrom Stack Overflow: asked by Swaroop C H, answered by Shonzilla (CC BY-SA 3.0)

  22. Should I use Singular or Plural name convention for REST resources?

    For me is better to have a schema that you can map directly to code (easy to automate), mainly because code is what is going to be at both ends.

    GET  /orders          <---> orders 
    POST /orders          <---> orders.push(data)
    GET  /orders/1        <---> orders[1]
    PUT  /orders/1        <---> orders[1] = data
    GET  /orders/1/lines  <---> orders[1].lines
    POST /orders/1/lines  <---> orders[1].lines.push(data) 
    

    From Stack Overflow: asked by JPReddy, answered by jla (CC BY-SA 3.0)

  23. Best Practices for securing a REST API / web service

    As tweakt said, Amazon S3 is a good model to work with. Their request signatures do have some features (such as incorporating a timestamp) that help guard against both accidental and malicious request replaying.

    The nice thing about HTTP Basic is that virtually all HTTP libraries support it. You will, of course, need to require SSL in this case because sending plaintext passwords over the net is almost universally a bad thing. Basic is preferable to Digest when using SSL because even if the caller already knows that credentials are required, Digest requires an extra roundtrip to exchange the nonce value. With Basic, the callers simply sends the credentials the first time.

    Once the identity of the client is established, authorization is really just an implementation problem. However, you could delegate the authorization to some other component with an existing authorization model. Again the nice thing about Basic here is your server ends up with a plaintext copy of the client's password that you can simply pass on to another component within your infrastructure as needed.

    From Stack Overflow: asked by Nathan, answered by Greg Hewgill (CC BY-SA 2.5)

  24. What's the difference between REST & RESTful?

    Representational state transfer (REST) is a style of software architecture. As described in a dissertation by Roy Fielding, REST is an "architectural style" that basically exploits the existing technology and protocols of the Web.

    RESTful is typically used to refer to web services implementing such an architecture.

    From Stack Overflow: asked by AwkwardCoder, answered by Justin Ethier (CC BY-SA 2.5)

  25. What's the difference between text/xml vs application/xml for webservice response?

    From the RFC (3023), under section 3, XML Media Types:

    If an XML document -- that is, the unprocessed, source XML document -- is readable by casual users, text/xml is preferable to application/xml. MIME user agents (and web user agents) that do not have explicit support for text/xml will treat it as text/plain, for example, by displaying the XML MIME entity as plain text. Application/xml is preferable when the XML MIME entity is unreadable by casual users.

    (emphasis mine)

    From Stack Overflow: asked by Mike, answered by Oded (CC BY-SA 4.0)

  26. 400 vs 422 response to POST of data

    400 Bad Request would now seem to be the best HTTP/1.1 status code for your use case.

    At the time of your question (and my original answer), RFC 7231 was not a thing; at which point I objected to 400 Bad Request because RFC 2616 said (with emphasis mine):

    The request could not be understood by the server due to malformed syntax.

    and the request you describe is syntactically valid JSON encased in syntactically valid HTTP, and thus the server has no issues with the syntax of the request.

    However as pointed out by Lee Saferite in the comments, RFC 7231, which obsoletes RFC 2616, does not include that restriction:

    The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

    However, prior to that re-wording (or if you want to quibble about RFC 7231 only being a proposed standard right now), 422 Unprocessable Entity does not seem an incorrect HTTP status code for your use case, because as the introduction to RFC 4918 says:

    While the status codes provided by HTTP/1.1 are sufficient to describe most error conditions encountered by WebDAV methods, there are some errors that do not fall neatly into the existing categories. This specification defines extra status codes developed for WebDAV methods (Section 11)

    And the description of 422 says:

    The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions.

    (Note the reference to syntax; I suspect 7231 partly obsoletes 4918 too)

    This sounds exactly like your situation, but just in case there was any doubt, it goes on to say:

    For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

    (Replace "XML" with "JSON" and I think we can agree that's your situation)

    Now, some will object that RFC 4918 is about "HTTP Extensions for Web Distributed Authoring and Versioning (WebDAV)" and that you (presumably) are doing nothing involving WebDAV so shouldn't use things from it.

    Given the choice between using an error code in the original standard that explicitly doesn't cover the situation, and one from an extension that describes the situation exactly, I would choose the latter.

    Furthermore, RFC 4918 Section 21.4 refers to the IANA Hypertext Transfer Protocol (HTTP) Status Code Registry, where 422 can be found.

    I propose that it is totally reasonable for an HTTP client or server to use any status code from that registry, so long as they do so correctly.

    Read the rest at the sourceFrom Stack Overflow: asked by David S, answered by Kristian Glass (CC BY-SA 4.0)

  27. Should a RESTful 'PUT' operation return something....

    The HTTP specification (RFC 2616) has a number of recommendations that are applicable. Here is my interpretation:

    • HTTP status code 200 OK for a successful PUT of an update to an existing resource. No response body needed. (Per Section 9.6, 204 No Content is even more appropriate.)
    • HTTP status code 201 Created for a successful PUT of a new resource, with the most specific URI for the new resource returned in the Location header field and any other relevant URIs and metadata of the resource echoed in the response body. (RFC 2616 Section 10.2.2)
    • HTTP status code 409 Conflict for a PUT that is unsuccessful due to a 3rd-party modification, with a list of differences between the attempted update and the current resource in the response body. (RFC 2616 Section 10.4.10)
    • HTTP status code 400 Bad Request for an unsuccessful PUT, with natural-language text (such as English) in the response body that explains why the PUT failed. (RFC 2616 Section 10.4)

    Note: RFC 2616 was the latest specification when this answer was written, but the RFC has since been superseded. When referring to any standard, it can be useful to verify that you are using the latest one.

    From Stack Overflow: asked by AwkwardCoder, answered by system PAUSE (CC BY-SA 4.0)

  28. Do sessions really violate RESTfulness?

    First, let's define some terms:

    • RESTful:

      One can characterise applications conforming to the REST constraints described in this section as "RESTful".[15] If a service violates any of the required constraints, it cannot be considered RESTful.

      according to wikipedia.

    • stateless constraint:

      We next add a constraint to the client-server interaction: communication must be stateless in nature, as in the client-stateless-server (CSS) style of Section 3.4.3 (Figure 5-3), such that each request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client.

      according to the Fielding dissertation.

    So server side sessions violate the stateless constraint of REST, and so RESTfulness either.

    As such, to the client, a session cookie is exactly the same as any other HTTP header based authentication mechanism, except that it uses the Cookie header instead of the Authorization or some other proprietary header.

    By session cookies you store the client state on the server and so your request has a context. Let's try to add a load balancer and another service instance to your system. In this case you have to share the sessions between the service instances. It is hard to maintain and extend such a system, so it scales badly...

    In my opinion there is nothing wrong with cookies. The cookie technology is a client side storing mechanism in where the stored data is attached automatically to cookie headers by every request. I don't know of a REST constraint which has problem with that kind of technology. So there is no problem with the technology itself, the problem is with its usage. Fielding wrote a sub-section about why he thinks HTTP cookies are bad.

    From my point of view:

    • authentication is not prohibited for RESTfulness (otherwise there'd be little use in RESTful services)
    • authentication is done by sending an authentication token in the request, usually the header
    • this authentication token needs to be obtained somehow and may be revoked, in which case it needs to be renewed
    • the authentication token needs to be validated by the server (otherwise it wouldn't be authentication)

    Your point of view was pretty solid. The only problem was with the concept of creating authentication token on the server. You don't need that part. What you need is storing username and password on the client and send it with every request. You don't need more to do this than HTTP basic auth and an encrypted connection:

    • Figure 1. - Stateless authentication by trusted clients

    You probably need an in-memory auth cache on server side to make things faster, since you have to authenticate every request.

    Now this works pretty well by trusted clients written by you, but what about 3rd party clients? They cannot have the username and password and all the permissions of the users. So you have to store separately what permissions a 3rd party client can have by a specific user. So the client developers can register they 3rd party clients, and get an unique API key and the users can allow 3rd party clients to access some part of their permissions. Like reading the name and email address, or listing their friends, etc... After allowing a 3rd party client the server will generate an access token. These access token can be used by the 3rd party client to access the permissions granted by the user, like so:

    • Figure 2. - Stateless authentication by 3rd party clients

    Read the rest at the sourceFrom Stack Overflow: asked by deceze, answered by inf3rno (CC BY-SA 3.0)

  29. When do I use path parameters vs. query parameters in a RESTful API?

    TL;DR: The best practice for RESTful API design is that path parameters are used to identify a specific resource or resources, while query parameters are used to sort/filter those resources.

    Here's an example. Suppose you are implementing RESTful API endpoints for an entity called Car. You would structure your endpoints like this:

    GET /cars
    GET /cars/:id \ POST /cars \ PUT /cars/:id \ DELETE /cars/:id

    This way, you are only using path parameters when you are specifying which resource to fetch, but this does not sort/filter the resources in any way.

    Now suppose you wanted to add the capability to filter the cars by color in your GET requests. Because color is not a resource (it is a property of a resource), you could add a query parameter that does this. You would add that query parameter to your GET /cars request like this:

    GET /cars?color=blue

    This endpoint would be implemented so that only blue cars would be returned.

    We can add more filtering parameters using the & symbol:

    GET /cars?color=blue&brand=ferrari

    As far as syntax is concerned, your URL names should be all lowercase. If you have an entity name that is generally two words in English, you would use a hyphen to separate the words, not camel case.

    Example /two-words

    From Stack Overflow: asked by cosbor11, answered by Mike (CC BY-SA 4.0)

  30. What is the proper REST response code for a valid request but empty data?

    TL;DR: Use 404

    See This Blog. It explains it very well.

    Summary of the blog's comments on 204:

    1. 204 No Content is not terribly useful as a response code for a browser (although according to the HTTP spec browsers do need to understand it as a 'don't change the view' response code).
    2. 204 No Content is however, very useful for ajax web services which may want to indicate success without having to return something. (Especially in cases like DELETE or POSTs that don't require feedback).

    The answer, therefore, to your question is use 404 in your case. 204 is a specialized reponse code that you shouldn't often return to a browser in response to a GET.

    The other response codes are even less appropriate than 204 and 404:

    1. 200 should be returned with the body of whatever you successfully fetched. Not appropriate when the entity you're fetching doesn't exist.
    2. 202 is used when the server has begun work on an object but the object isn't fully ready yet. Certainly not the case here. You haven't begun, nor will you begin, construction of user 9 in response to a GET request. That breaks all sorts of rules.
    3. 400 is used in response to a poorly formatted HTTP request (for instance malformed http headers, incorrectly ordered segments, etc). This will almost certainly be handled by whatever framework you're using. You shouldn't have to deal with this unless you're writing your own server from scratch. Edit: Newer RFCs now allow for 400 to be used for semantically invalid requests.

    Wikipedia's description of the HTTP status codes are particularly helpful. You can also see the definitions in the HTTP/1.1 RFC2616 document at www.w3.org

    From Stack Overflow: asked by IMB, answered by Chris Pfohl (CC BY-SA 4.0)

After the last page: 11 questions more, without answers. Go to the last page

Related topics

Where these questions come from

Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.