RESTful API Design, RESTful URI Design, Design Steps, Example Application, What are resources in REST? Various HTTP Status codes used in REST, POST, GET, PUT, PATCH, DELETE methods and what are they used for?
2. Part I - Recap
1. Architectural Constraints of REST
a. Client-Server
b. Statelessness
c. Cacheability
d. Layered System
e. Code-on-Demand
f. Uniform Interface
2. All about Resources
a. What is a resource?
b. Types of resources
3. All about Representations
4. URI Naming Conventions
3. RESTful API design steps
1. Identify the resource(s).
○ What are resources?
2. Create model URIs.
○ versioning, namespace, resources naming conventions and resource identifiers.
3. Determine resource structure and request/response format.
4. Assign HTTP methods
○ HTTP methods and status codes.
○ Idempotency, Safety and caching responses.
4. Example Application
● We are going to build a simple user service, where we store, retrieve and
modify user information.
● User information includes - name, DOB, list of their addresses, password,
phone#, email, type and status of their account.
5. Resources
● What are resources?
○ General Definition - A resource is anything that’s important enough to be referenced as a
thing. You should make something into a resource, if you want to
■ include all or part of it by reference into another representation,
■ retrieve or cache a representation of it,
■ create a hypertext link to it,
■ or perform CRUD operations on it.
○ Definition of a resource was designed to be intentionally vague. So, if you don’t understand it,
get in line.
○ In RESTful APIs resources can be collections or singletons, they can also contain other
resources.
8. URIs
● URIs are used to uniquely identify and address a resource in RESTful APIs.
● URIs are made up of 3 parts.
○ Version,
○ Namespace (optional),
○ Resource name.
● We’ll look into what each of the above concepts are, in detail in the following
slides.
9. More About URIs - Versioning
● APIs are a contract between the client and the server (uniform interface constraint).
● Breaking changes break the contract between the client and the server. In our case, between our
frontend react application and our backend java services.
● Breaking changes include -
○ a change in the format of the request/response data for one or more calls
○ a change in the request/response type (i.e. changing an integer to a float) etc.
● Non-breaking changes tend to be additive. E.g. adding new fields or nested resources to your
resource representations, adding new endpoints such as a PUT or PATCH that was previously
unavailable. API consumers should build client code that is resilient to these kinds of non-breaking
changes.
10. Versioning continued...
● Version changes should happen according to the following rules, when your
APIs are being consumed by clients.
○ Breaking changes result in a major version change.
○ Non-breaking changes result in a minor version change (optional).
● Version changes should not happen during the development phase of your
APIs. I.e. before exposing them to the client.
● Since we are in the process of developing our example application, we will
use v1 as our API version.
11. More About URIs - Namespaces
● Namespaces are optional and add a bit of organisation to your APIs mainly
from a documentation point of view.
● Namespaces allow you to group related resources under a common root.
● It can be used for url based routing when there are multiple components (E.g.
microservices).
● Also allows you to define a scope for a particular resource.
○ E.g. In our inhouse IoT application, In case you want to differentiate between motor
configuration and sump configuration, you can use the same resource name under 2
namespaces -
■ /v1/motor/configurations
■ /v1/sump/configurations
● Namespaces should be singular nouns.
12. Resource naming and URI formatting best practices
● Use nouns for collections and document names, and verbs for controllers
names
○ E.g. collection - /v1/motor/configurations, controller - /v1/motor/change-configuration
● Forward slash (/) to indicate hierarchical relationships.
● Avoid trailing slashes
● Use hyphens to improve readability
● Do not use underscores in URIs
● Use lower case in URIs
● Do not use file extensions
● Never use camel case CRUD function names in URIs
○ E.g. Correct - POST /v1/motor/configurations, Wrong - /v1/motor/createConfigurations,
● Use query params to filter collection type resources.
13. Resource naming recap
● Plural lowercase nouns.
● DO NOT use verbs in resource names. E.g. /v1/device/getDeviceInfo
● DO NOT use camel case.
● Use hyphens in between words, in case there more than 2 words in your
resource name.
● Use resource ids to identify particular resources in a collection. E.g.
/v1/device/{id}.
● Subresources are identified like this /v1/device/{id}/configurations
14. URIs for our example application
● Recap - Resources that we identified were user and address (sub-resource).
● URIs are made up of 3 parts,
○ Version,
○ Namespace (optional in general, but mandatory for our example app),
○ Resource name.
● Can you name the URIs that we will use in our application?
● Remember URIs are used to address a particular resource uniquely.
15. URIs for our example application
● /v1/account/users and /v1/account/users/{id}/addresses
● /v1/account/addresses
16. Request/Response Format
● Now we need to take a decision on how we are going to represent our
resources.
● REST accepts multiple request and response body types, like form-url-
encoded, form data, plain text, json, binaries etc.
● Most RESTful APIs use either XML or JSON.
● We are going to be using JSONs in our example application.
17. Idempotence, Safety and Caching
● In computing, an idempotent operation is one that has no additional effect if it is called more than
once with the same input parameters. f(f(f(x))) = f(x).
● E.g. the abs function is idempotent because abs(abs(x)) = abs(x).
● In RESTful APIs a request method is considered "idempotent" if the intended effect on the server of
multiple identical requests with that method is the same as the effect for a single such request.
● Is the DELETE method idempotent?
● A Safe method does not modify the given resource in any way. It retrieves a representation of a
given resource without modifying it.
● “Cacheability” is one of REST’s architectural constraints.
● In RESTful APIs, when a consumer requests a resource’s representation, the request goes through
a cache or a series of caches before hitting the database hosting the resource.
18. HTTP methods and response codes
● HTTP methods represent the ways in which resources can be accessed or
modified.
● There are 5 major HTTP methods
a. POST
b. GET
c. PUT
d. PATCH
e. DELETE
● In addition to response messages, server responses also contain http
headers, a status message and a status code.
● Status codes range from 1xx - 5xx
19. HTTP Status Codes
HTTP Status Codes Description
1xx (Informational) An informational response, indicates that the request was received and
understood.
2xx (Successful) The request was successfully received, understood and accepted.
3xx (Redirection) Further action needs to be taken in order to complete the request.
4xx (Client Error) The request contains bad syntax or cannot be fulfilled.
5xx (Server Error) The server failed to fulfill an apparently valid request.
20. Status Codes continued...
● 1xx - Informational
○ 101 Switching Protocols
● 2xx - Successful,
○ 200 OK
○ 202 Accepted
○ 201 Created
○ 204 No Content
● 3xx - Redirection,
○ 301 Moved Permanently
○ 302 Found
○ 304 Not Modified
● 4xx - Client Errors,
○ 400 Bad Request
○ 401 Unauthorized
○ 403 Forbidden
○ 404 Not Found
● 5xx - Server Errors.
○ 500 Internal Server Error
○ 502 Bad Gateway
○ 504 Gateway Timeout
For More Info visit -
https://tools.ietf.org/html/rfc2616#section-10
21. POST
● POST method is used to create new resources.
● If the resource is created, the server responds with a 201 Created.
● Sometimes when a POST request performs an action on a resource without a
resource identifier (controller pattern methods) the server can return a 200
(OK) or a 204 (No Content).
● POST responses are not cacheable.
● POST request are neither safe nor idempotent and invoking two identical
POSTs will result in two different resources containing the same information
and different resource ids.
● POSTs cannot return 404.
22. GET
● GET Request are used to retrieve resource representations (current state of the
resource).
● There are 2 types of GET requests.
a. GET with resource identifier,
b. GET for a collection of resources with or without query params.
● GETs usually return a 200 OK with the response body containing the resource(s) that
were requested.
● Type 1 GET (get with id) should return a 404 Not Found, if the requested resource is
not present in the server.
● Type 2 GET (get collection) should return a 200 with an empty response body, if the
requests resources are not found.
● GET is idempotent, safe and the responses are cacheable.
23. ● PUT request are used to update existing resources.
● If the resource does not exist, the server may choose to create it or it may not.
● If a resource was created, the server must return a 201 Created to inform the client,
that the update resulted in a new resource being created.
● If an existing resource was updated, the server can return either a 200 OK or a 204 No
Content.
● PUT should only be used if you are replacing an entire resource, for partial updates
please use the PATCH method.
● PUT
○ requests are idempotent but are not safe
○ response is not cacheable.
PUT
24. PATCH
● It is used to partially update a resource.
● It cannot create a resource as it sends partial information only.
● PATCH applies a delta rather than updating the given resource entirely.
● A typical PATCH request is an array of partial modifications to the given resource.
● The array contains a request to update a particular portion of a given resource in the
following format.
[{ “op”: “replace”, “path”: “/email”, “value”: “new.email@example.org” }]
● op is operation, it can be remove, add, replace, move and copy.
● It includes the path to the field that you are changing and the value that needs to be
changed.
● Similar to PUT, PATCH requests are also idempotent, not safe and not cacheable.
JSON Patch standard -
https://tools.ietf.org/html/rfc6902
25. DELETE
● As the name applies, DELETE method is used to delete resources.
● A successful delete operation should return a 200 OK with a response or if
you don’t wish to return any response from the server, a 204 No Content is
sent back.
● DELETE operations are idempotent (ideally).
● If the item is not present in the server, it may return a 404 Not Found to the
client.
● It is also not cacheable and not safe.
26. Recap
HTTP Method Request Has Body Response Has Body Safe Idempotent Cacheable
POST Yes Yes No No No
GET No Yes Yes Yes Yes
PUT Yes Optional No Yes No
PATCH Yes Optional No Yes No
DELETE No Optional No Yes No
27. Back to our example application
● Recap - resource names - users and addresses which was a sub-resource.
● Endpoints - /v1/account/users and /v1/account/users/{id}/addresses.
● Can you make CRUD endpoints for the users and address resources?
● I need to get all addresses that have the pincode as 600014, how do i do
that?
● Also needed is an endpoint to modify the user’s mobile number. The request
should contain the user’s current mobile number, an otp and their updated
mobile number.
● Update a user’s DOB with a resource id and the updated DOB value alone.