Best Practices in API Design | Swagger
Your web API design is a competitive advantage. Clear communication of your API strategy and business model(s) to all lines of business to ensure . Use nested resources to indicate relationships between resources. Guidance on how to create a well-designed web API. (The article Data Partitioning describes strategies to scale out a data store.) Also consider the relationships between different types of resources and how you might. I've tried both design strategies - nested and non-nested endpoints. . is in a REST API is only interesting to you as the API developer, not the API client, as would the and it knowns what those relationships mean ("companies" mean a list of.
Whether you target internal developers, developers within a partner organization, or public developers in general, you are making a contract with each individual developer. Therefore, the documentation you provide to developers will provide the bulk of their developer experience. It will be the first thing that they experience when trying to understand your API, and the first place they go when they are stuck.
The challenge with API documentation is that it must serve a variety of situations. This may include the developer looking at your API for the first time or the expert developer looking to use a newly released feature.
This means that complete documentation takes into account the following scenarios: This is particularly the case when using documentation written inline with the code itself. Tools exist that allow API docs to be built from inline comments and are sometimes used to expedite the documentation process. However, the result is documentation that is only focused on what that specific code does, not how to use it successfully. Complete documentation must consider all of the five scenarios previously listed.
Interactive Finally, great documentation should be interactive. But another added benefit is that we can use the browser to actually interact with our API. API documentation using Swagger, which offers a Try It Out feature Interactive API documentation allows anyone, including developers, quality assurance staff, product managers, and support staff to make API calls into a live running server from within the documentation itself.
Imagine allowing developers and QA staff explore your API before they ever write a line of code or an automated test! That is power of interactive documentation. By lowering the learning curve of your API, you will ensure that developers experience successes early and often. This results in greater API adoption, longer retention even in the face of competitorsand developer autonomy resulting in reduced support costs.
Follow these general guidelines to make your API more intuitive: Make data available easily, rather than hidden or hard to find. Require only the information necessary to accomplish the desired task. Offer both low-level ways of getting things done, as well as higher-level ways of accomplishing common workflows with fewer calls. Use hypermedia links to inform API clients the available actions at any given point, based on the current state of the data and the permissions of the API client.
Offer only one way to accomplish a task. For APIs, consistency is important for a great developer experience because it creates predictability.
As developers start to become familiar with your API, they will come to expect the same familiarity as they explore it further. This consistency encompasses a number of areas, including naming, resource URLs, payload formats, and error messaging.
Consistent naming As developers approach your API, the first thing they will notice is the naming conventions that you use. This includes the names of the domain concepts referenced, many of which become the resources used in the URLs of your API. Therefore, naming is critical to the understanding and usage of your API.
The following are some tips for incorporating consistent naming: Avoid abbreviations, as they can be difficult to read and often create confusion as some names may be unclear or inconsistently abbreviated. Be consistent with resource names to avoid confusion.
Refrain from referencing internal systems, as this results in requiring insider knowledge to use or comprehend your API. It is highly recommended that you develop a resource ontology to ensure that URLs are consistently designed into the API.
If you are unfamiliar, ontology is a technique used in information science for the naming and typing of entities and their relationships. API ontologies define the structure of your API, from the top-level resources to the nested resources under them.
An example resource ontology for an eCommerce API When designing your resource ontology, apply the following techniques to create a more consistent API: Use plural resource names when offering a collection of resources and a singular resource name for a single resource e.
Use nested resources to indicate relationships between resources. Avoid one-off URLs e.
Consistent payload formats Finally, the payload format should be consistent to allow API consumers to easily construct request payloads and parse response payloads. Most developers prefer to write helper code to handle this logic. If an API is inconsistent in its approach, developers will have to write one-off code to handle the differences. Follow these patterns for more consistent API payloads: Reuse field names across payloads when possible for better predictability e. Avoid abbreviations in field names.
Select a single payload format or standard when handling payloads, including resource representations and search result collections. Ensure all error message formats are consistent across the API. This is especially important when an API is built by multiple developers who may otherwise handle error messaging differently.
While data is important, developers seek out APIs to solve a problem. If they wanted to store data, they would push it into a database directly, unless you have data that no one else can provide. This may be solving difficult problems, building support for collaboration, or providing data analysis. Great APIs need to look beyond data access endpoints. While these kinds of endpoints are essential to any API, adding workflow into your API helps developers get things done quickly and with fewer lines of code.
As an example, Twilio only supported conference calls by putting each caller on mute and then managing each caller using the low-level access APIs. The company realized that customers required an affordance to support conference calls at a higher level. The result is that providers were able to remove a lot of hard work from API developers by building in a higher-level conference call API that did the heavy lifting for them. PUT requests must be idempotent. If a client submits the same PUT request multiple times, the results should always be the same the same resource will be modified with the same values.
However, it doesn't cover every possible detail or scenario. When in doubt, consult the HTTP specifications. Media types As mentioned earlier, clients and servers exchange representations of resources. For example, in a POST request, the request body contains a representation of the resource to create. In a GET request, the response body contains a representation of the fetched resource.
The Content-Type header in a request or response specifies the format of the representation. A client request can include an Accept header that contains a list of media types the client will accept from the server in the response message. If the resource cannot be found, the method should return Not Found. The URI of the new resource is included in the Location header of the response. The response body contains a representation of the resource.
If the method does some processing but does not create a new resource, the method can return HTTP status code and include the result of the operation in the response body.
Alternatively, if there is no result to return, the method can return HTTP status code No Content with no response body. The response body can contain additional information about the error or a link to a URI that provides more details. If the method updates an existing resource, it returns either OK or No Content. In some cases, it might not be possible to update an existing resource.
The PUT request should specify the URI of the collection, and the request body should specify the details of the resources to be modified. This approach can help to reduce chattiness and improve performance.
The server processes the patch document to perform the update. The patch document doesn't describe the whole resource, only a set of changes to apply. The format must be inferred from the media type in the request. JSON merge patch is somewhat simpler. The patch document has the same structure as the original JSON resource, but includes just the subset of fields that should be changed or added. In addition, a field can be deleted by specifying null for the field value in the patch document.
That means merge patch is not suitable if the original resource can have explicit null values. For example, suppose the original resource has the following JSON representation: Merge patch is not suitable if the original resource can contain explicit null values, due to the special meaning of null in the patch document. Also, the patch document doesn't specify the order that the server should apply the updates. That may or may not matter, depending on the data and the domain.
It specifies the changes as a sequence of operations to apply. Operations include add, remove, replace, copy, and test to validate values. Error condition The patch document format isn't supported. If you wait for completion before sending a response to the client, it may cause unacceptable latency.
If so, consider making the operation asynchronous. Return HTTP status code Accepted to indicate the request was accepted for processing but is not completed. You should expose an endpoint that returns the status of an asynchronous request, so the client can monitor the status by polling the status endpoint.
Include the URI of the status endpoint in the Location header of the response. Optionally, it could also include an estimated time to completion or a link to cancel the operation. In the response, include a Location header that gives the URI of the new resource: Filter and paginate data Exposing a collection of resources through a single URI can lead to applications fetching large amounts of data when only a subset of the information is required.
api design - What are best practices for REST nested resources? - Stack Overflow
For example, suppose a client application needs to find all orders with a cost over a specific value. Clearly this process is highly inefficient. It wastes network bandwidth and processing power on the server hosting the web API.
This example response should be simple, plain, and quick to comprehend.
API design guidance - Best practices for cloud applications | Microsoft Docs
A good rule of thumb is to help developers understand exactly what a successful response would give them in under five seconds. Successfully returned information about users schema: The successful response an end user would receive in JSON would look as follows. Likewise, an incorrect call should produce an appropriate or response code with relevant information to help user better operate against the collection.
These properties describe the base resource and isolate specific assets of information that can be manipulated with the appropriate method. An API should strive towards completion, and provide all the required information, data and resources to help developers integrate with them in a seamless manner. But completion means taking into account common use cases for your API. The amount of data the resource exposes should also be taken into account.
The above cases and relationships are important considerations in the design of the API, and can be handled using the appropriate parameters. Let's take the example of our photosharing app.