REST

Cards (34)

  • What is REST?
    • REST is an architectural style, not a standard.
    • REST APIs typically adhere to common web HTTP concepts.
    • Message payloads generally use JSON (Javascript Object Notation).
    • REST is currently the most common style of web API.
    • APIs that follow the REST architectural style are called RESTful.
  • SOAP, or Simple Object Access Protocol, was a popular way to implement APIs. SOAP, however, is not very simple. In order to make an API call using the SOAP protocol, a developer needs to craft a complex XML payload by referencing an even more complex definition document called a WSDL, which stands for Web Services Description Language.
    • REST APIs leverage common web HTTP concepts like URLs, verbs, and status codes.
    • Message payloads for REST APIs are generally specified using simple JavaScript Object Notation, or JSON. The JSON payload of a well-written REST API is simpler and more human-readable than the complex XML used for SOAP services.
  • REST API
    Resources:
    • /orders // list of orders
    • /orders/{id} // specific order
    Verbs
    • GET // retrieve/search
    • PUT/PATCH // update
    • DELETE // remove
    • POST // create
  • REST APIs:
    • RESTful APIs are resource-oriented, focusing on the resources being acted upon, instead of focusing on a list of operations or actions.
    • Resources are specified in API URLs by using resource names and IDs. For example, to access a list of orders, you would make a request to "/orders." To access order 1234, you would make a request to "/orders/1234."
    • The request's HTTP verb, or method, specifies the type of operation that is being performed on the resource or list of resources.
  • REST APIs:
    • Normal browser requests to retrieve web pages use the verb GET. A GET request for a RESTful API therefore retrieves details about the resource or resources specified in the URL.
    • POST is used to create a new entity. POSTing to "/orders" would typically create a new order with an auto-generated ID.
    • PUT or PATCH to "/orders/id" is used to update an existing order, and DELETE on "/orders/id" would remove the order.
  • GET https://api.example.com/sales/customers
    • This API request is using the domain name api.example.com, and the beginning of the URL path is "/sales." For a REST API, the first part of the URL specifies the particular API that is being called. So this is example.com's sales API.
    • After "/sales," we see "/customers." This follows the resource pattern we saw earlier. "/customers" represents a list of customers. We are using the GET verb, so this request is fetching a list of customers.
  • GET https://api.example.com/sales/customers: Response:
    • 200 is the response status code, and OK is the reason phrase. The status code indicates the success or failure of the request, as well as the type of failure, if the request failed. Since the API returned 200 OK, the API call succeeded
    • The Content-Type header specifies the type of data returned in the payload: JSON, in this case. The Cache-Control header specifies how long the requestor can cache and use this response instead of having to make the same request again.
  • API Response:
    • After the headers is the response payload. The JSON response is showing a list of customers, with an ID, name, and reference for each. The href reference is a URL that can be used to retrieve more details about that customer.
    • that can be used to retrieve more details about that customer.
  • GET /customers/C72
    • This retrieves information for a specific customer, in this case Joe Apigeek, who has an ID of C72.
    • In this example, we retrieve much more than just the name, ID, and a reference, since we are requesting the details of a single customer instead of up to 100 of them. This response also includes links, which allow us to easily retrieve the orders or wishlist of Joe Apigeek.
    • When you design your own APIs, think about how your app developers would want to consume your APIs, and what data would be useful to them. Remember, your app developers are your customers.
  • API Resources:
    • Prefer concrete names over abstractions
    • Two primary URLs per resource type/employees is a collection /employees/1234 is a single entity
    • Use plural nouns for resource names /employees/1234, NOT /employee/1234
    • Prefer standard terms over internal company terminology/employees, NOT /apigeeks
  • API Resources:
    • Resources typically use concrete names instead of abstractions. In an employee API, your resources might include employees, buildings, and reporting relationships.
    • Each resource type typically has two primary URLs: /employees would be a collection of employees, and /employees/1234 would be the specific employee with the unique ID 1234.
    • We use plural nouns for resource names in the URL. Use the plural noun for the collection name, "/employees," as well as for a specific employee, "/employees/1234."
  • API Operations:
    • GET is the verb used to retrieve information about a collection of resources or a single resource. When you retrieve a web page in your browser, you are using the GET verb.
    • A GET should not update the state of the resource at all.An operation that does not update the state is known as a safe method.
    • Unless another API call has modified the state of your resource between calls, repeating the same GET call will always produce the same result.
    • We call this being "idempotent."
  • API Operations:
    • POST on "/dogs" is used to create a new dog. No id is provided in the URL; the id for the new dog should be automatically generated by the API.
    • The POST method modifies the state of resources, creating a new resource in the dogs collection. Therefore, POST is not a safe method.
    • Repeating the same POST call will result in multiple dogs being created, so POST is also not idempotent.
    • POSTing to a specific dog by id does not have a specific CRUD meaning.
  • API Operations:
    • For update, we have two methods listed: PUT and PATCH. We will focus on the differences between PUT and PATCH later.
    • "PUT /dogs/1234" would update Toto, the dog with id 1234.
    • If appropriate for your API, you can have PUT create a new resource with the specified id if one doesn't already exist. This is somewhat rare: typically this would only be used when the id of a resource is a unique number or string, like a product ID.
  • API Operations:
    • "PUT /dogs" would bulk update all dogs, or matching dogs if your request included a search or filter. Do not allow this operation unless it is necessary, because it might be too easy to accidentally bulk update lots of dogs
    • PUT is not a safe method, because it is meant to update resources.
    • PUT, however, is specified by HTTP as an idempotent method. A second identical PUT call should therefore leave the resource or resources in the same state.
  • API Operations:
    • The DELETE method is used to delete a resource. "DELETE /dogs/1234" would delete a specific dog.
    • "DELETE /dogs" would delete all dogs, or all dogs that match the search or filters provided. Most APIs don't allow a DELETE on a collection, because it would be too easy to accidentally delete everything in the collection.
    • DELETE updates the state by removing resources, so it isn't safe.
    • A second identical delete has no effect, since the resource was already deleted, so DELETE is idempotent.
  • Keep verbs out of URLs
    • URLs with verbs are difficult to remember
    • Use primary verbs (GET, POST, PUT/PATCH, DELETE) with noun-oriented resources for CRUD operations.
    • For non-CRUD operations, consider using a query parameter to perform an action on a resource:
    • POST /dogs/1234?action=walk
    • POST /dogs/1234?action=feed&object=treat
  • PUT & PATCH
    • The HTTP PUT and PATCH verbs are both used to update resources, but for HTTP they have different behaviors.
    • PUT completely replaces a resource with the provided payload. PATCH should only be used to modify a subset of the resource. The JSON Merge Patch specification specifies how PATCH can be used for partial updates. Fields with a value are added or modified, and fields specified as null are deleted. Fields not mentioned in the PATCH request are not modified.
  • PUT & PATCH:
    • Performing a GET on the widget with id of 1, we see that the widget's name is Bob, and its count is 14. The PATCH call updates resource 1, setting the size field to large, and removing the count field since it is null. The name field is unchanged. The PUT call replaces the entire resource with the request payload.
  • When you look at public REST APIs, most tend to use the PUT verb, even though they are actually using the semantics of HTTP PATCH, where fields that are not present in the request payload are not modified. Although this is not the standard HTTP use of PUT, it is very common in REST APIs.
    • When you are creating your own APIs, consider using PATCH for partial updates. However, it helps your app developers if you maintain consistency for your APIs, so you may decide to use PUT for partial updates if other APIs are also using PUT in this way
  • '?'
    • Use query parameters instead of repetitive calls.
    • Which would you rather use?
  • Query Parameters:
    GET /dogs?location=park&color=brown&state=running
    • Coming up with the second solution requires the API developer to think like the app developer, and think about the experience of a user of an app that consumes your API. It is worth your time to think and design your APIs using this mindset. Also, APIs may be used by apps in ways you didn't originally expect. You can add features to your APIs to address needs as you learn of them, either when requested by your app developers, or by analyzing API call patterns.
  • Partial Responses:
    • Another way to deliver an optimized experience to your app developers is to allow the selection of partial responses. Instead of returning the entire response every time, you can give the developer control over which fields to return. This feature should definitely be considered for APIs that are designed for usage in low bandwidth apps, like mobile apps, or for APIs with large response payloads. In this example, a list of comma-separated fields is specified using a query parameter, and only the requested fields are returned in the response.
  • API-first development
    • Design from the perspective of API users ○ Not the backend API design
    • Design API interface first ○ Implementation to follow
    • API-first development is a strategy where your APIs are designed by first focusing on the needs of the app developers who will consume your API. Your API will be more successful if your app developers enjoy using your API and it solves their problems.
  • Traditional API development has often been driven by inside-out thinking: build services first, and then worry about how to expose them to the customer. A traditional goal may sound something like: "There are 20 APIs we use in our company, and we want to expose them to the world." This is focusing on the implementation of the API first, instead of focusing on the needs of the application developers who will be the customers of your APIs.
  • In contrast, if you adopt an API-first approach, you are basing your API design decisions on the needs of your potential customers.
    • This is outside-in thinking: designing with value for the customer as your primary focus, and then building something to deliver that value.
    • Concentrate your API design efforts on how your API will be consumed by your app developers and their applications.
  • API-First Benefits:
    • By designing your API contracts before you implement the APIs, you can have customers and stakeholders uncover business and technical gaps in your APIs before you develop them. You won't spend time building features that are not needed, and you won't design backend systems without understanding how they will be used.
    • This early review cycle also allows your APIs to be reviewed for consistency, usability, and best practices. Consistency across your APIs tends to increase adoption and give app developers confidence in your API program.
  • API First:
    • Designing the API contract early also increases the ability to do parallel development. Apps using the APIs can be designed, and use cases can be validated, while your API implementation is in progress.
  • Open API
    • In the early days, JSON-based APIs were documented using WADL, which stands for Web Application Description Language. WADL served a purpose similar to WSDL, or Web Services Description Language, which is used to describe SOAP-based services. Like WSDL, WADL is relatively difficult to use: it is XML-based, complex, and not very human-readable.
  • Open API
    • Swagger 2.0 introduced support for the YAML format. YAML is a recursive acronym which stands for YAML Ain't Markup Language. YAML is more human-readable than JSON.
    • Swagger 2.0 also provided the ability to describe all aspects of a RESTful API within a single file.
    • OpenAPI 3 further improved the structure and reusability of the components in an OpenAPI specification, and also added features like examples and callbacks. Apigee currently supports OpenAPI version 2 and 3.
  • Open API
    • OpenAPI specifications are a great way to document your REST APIs. OpenAPI specs describe the API interface, or contract, that defines how apps can use the API. An OpenAPI spec is laid out in a format that promotes readability and editability. OpenAPI specs define the available paths to resources and the allowed operations for each path.
    • The request and response formats for all API calls should be documented in the spec, including success and failure response codes and payload formats for all failure types.
  • OpenAPI specs in Apigee
    • OpenAPI specifications are used to provide interactive documentation for application developers in the developer portal. Being able to try your API streamlines the learning process for your app developers.
    • OpenAPI specifications can also be used to generate Apigee API proxy stubs. The generated proxy stubs will include flows for all resources and operations documented in the API specification.
  • OpenAPI specs in Apigee
    • You can also use an OpenAPI spec validation policy in your API proxy to validate incoming requests against an OpenAPI specification. Any requests that do not match the spec could be rejected.