REST.pdf
Document Details
Uploaded by Deleted User
Full Transcript
REST REST is an architectural style for designing networked applications. It was introduced by Roy Fielding in his doctoral dissertation in 2000. REST defines a set of constraints and principles for creating web services that are scalable, simple, and stateless. It does not depend on any specific...
REST REST is an architectural style for designing networked applications. It was introduced by Roy Fielding in his doctoral dissertation in 2000. REST defines a set of constraints and principles for creating web services that are scalable, simple, and stateless. It does not depend on any specific protocol, but it’s most commonly used over HTTP. RESTful RESTful refers to web services or APIs that are built adhering to the principles and constraints of REST. Practical Implementation: When you build an API using the REST architectural style, that API is referred to as RESTful. If you design an API that uses HTTP methods (GET, POST, PUT, DELETE) to interact with resources, returns representations like JSON or XML, and is stateless, it is a RESTful API. REST RESTful is a set of architectural principles refers to APIs or web services that that govern how web services follow the principles of REST. should be designed. How are REST APIs Stateless? HTTP Method RESTful HTTP Codes What is URI? Best practices in making URI for RESTful web services? Tools to develop and test REST APIs? Statefulness and Statelessness Statefulness and Statelessness are key concepts in software architecture, especially in the context of web applications and services. Understanding the difference between them is crucial for designing scalable and resilient systems. Statelessness Statefulness Statelessness means that each Statefulness means that the server request from a client to a server is retains information about the independent of any other request. client's state across multiple The server does not store any requests. The server can remember information about previous requests previous interactions with a client, from the same client. Each request making it possible to maintain must contain all the information session information. needed to understand and process it. HTTP METHOD HTTP defines a set of request methods to indicate the purpose of the request and what is expected if the request is successful. Although they can also be nouns, these request methods are sometimes referred to as HTTP verbs. Each request method has it's own semantics, but some characteristics are shared across multiple methods, specifically request methods can be safe, idempotent, or cacheable. METHOD POST GET PUT DELETE HEAD CONNECT OPTIONS TRACE PATCH POST The POST method submits an entity to the specified resource, often causing a change in state or side effects on the server. Characteristics: Not Idempotent: Multiple identical requests may result in multiple resources being created. Unsafe: Alters the state of the server. Not Cacheable: Typically, POST responses are not cached. GET The GET method requests a representation of the specified resource. Requests using GET should only retrieve data and should not contain a request Characteristics: Idempotent: Multiple identical requests have the same effect as a single request. Safe: Does not alter the state of the server. Cacheable: Responses can be cached for improved performance. PUT The PUT method replaces all current representations of the target resource with the request content. Characteristics: Idempotent: Multiple identical requests have the same effect as a single request. Unsafe: Alters the state of the server. Not Cacheable: Typically, PUT responses are not cached. DELETE The DELETE method deletes the specified resource. Characteristics: Idempotent: Multiple identical requests have the same effect as a single request. Unsafe: Alters the state of the server. Not Cacheable: Typically, DELETE responses are not cached. HTTP RESPONSE STATUS CODEs HTTP response status codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped in five classes: Response Codes Informational responses (100 – 199) Successful responses (200 – 299) Redirection messages (300 – 399) Client error responses (400 – 499) Server error responses (500 – 599) Informational responses (100 – 199) 100 Continue This interim response indicates that the client should continue the request or ignore the response if the request is already finished. 101 Switching Protocols This code is sent in response to an Upgrade request header from the client and indicates the protocol the server is switching to. 102 Processing (WebDAV) This code indicates that the server has received and is processing the request, but no response is available yet. 103 Early Hints This status code is primarily intended to be used with the Link header, letting the user agent start preloading resources while the server prepares a response or preconnect to an origin from which the page will need resources. Informational responses (100 – 199) 100 Continue This interim response indicates that the client should continue the request or ignore the response if the request is already finished. 101 Switching Protocols This code is sent in response to an Upgrade request header from the client and indicates the protocol the server is switching to. 102 Processing (WebDAV) This code indicates that the server has received and is processing the request, but no response is available yet. 103 Early Hints This status code is primarily intended to be used with the Link header, letting the user agent start preloading resources while the server prepares a response or preconnect to an origin from which the page will need resources. Redirection messages (300 – 399) 200 OK The request succeeded. The result meaning of "success" depends on the HTTP method: 201 Created The request succeeded, and a new resource was created as a result. This is typically the response sent after POST requests, or some PUT requests. 202 Accepted The request has been received but not yet acted upon. It is noncommittal, since there is no way in HTTP to later send an asynchronous response indicating the outcome of the request. It is intended for cases where another process or server handles the request, or for batch processing. 203 Non-Authoritative Information This response code means the returned metadata is not exactly the same as is available from the origin server, but is collected from a local or a third-party copy. This is mostly used for mirrors or backups of another resource. Except for that specific case, the 200 OK response is preferred to this status. 204 No Content There is no content to send for this request, but the headers may be useful. The user agent may update its cached headers for this resource with the new ones. Client error responses (400 – 499) 400 Bad Request 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). 401 Unauthorized Although the HTTP standard specifies "unauthorized", semantically this response means "unauthenticated". That is, the client must authenticate itself to get the requested response. 402 Payment Required Experimental This response code is reserved for future use. The initial aim for creating this code was using it for digital payment systems, however this status code is used very rarely and no standard convention exists. 403 Forbidden The client does not have access rights to the content; that is, it is unauthorized, so the server is refusing to give the requested resource. Unlike 401 Unauthorized, the client's identity is known to the server. Client error responses (400 – 499) 404 Not Found The server cannot find the requested resource. In the browser, this means the URL is not recognized. In an API, this can also mean that the endpoint is valid but the resource itself does not exist. Servers may also send this response instead of 403 Forbidden to hide the existence of a resource from an unauthorized client. This response code is probably the most well known due to its frequent occurrence on the web. 405 Method Not Allowed The request method is known by the server but is not supported by the target resource. For example, an API may not allow calling DELETE to remove a resource. 406 Not Acceptable This response is sent when the web server, after performing server-driven content negotiation, doesn't find any content that conforms to the criteria given by the user agent. Client error responses (400 – 499) 407 Proxy Authentication Required This is similar to 401 Unauthorized but authentication is needed to be done by a proxy. 408 Request Timeout This response is sent on an idle connection by some servers, even without any previous request by the client. It means that the server would like to shut down this unused connection. This response is used much more since some browsers, like Chrome, Firefox 27+, or IE9, use HTTP pre-connection mechanisms to speed up surfing. Also note that some servers merely shut down the connection without sending this message. 409 Conflict This response is sent when a request conflicts with the current state of the server. other : https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses Server error responses (500 – 599) 500 Internal Server Error The server has encountered a situation it does not know how to handle. 501 Not Implemented The request method is not supported by the server and cannot be handled. The only methods that servers are required to support (and therefore that must not return this code) are GET and HEAD. 502 Bad Gateway This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response. 504 Gateway Timeout This error response is given when the server is acting as a gateway and cannot get a response in time. Server error responses (500 – 599) 503 Service Unavailable The server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded. Note that together with this response, a user- friendly page explaining the problem should be sent. This response should be used for temporary conditions and the Retry-After HTTP header should, if possible, contain the estimated time before the recovery of the service. The webmaster must also take care about the caching-related headers that are sent along with this response, as these temporary condition responses should usually not be cached. URI A Uniform Resource Identifier (URI) is a string of characters used to identify a resource on Uniform Resource Identifier the Internet. URIs enable interaction with resources over a network, typically the World Wide Web, using specific protocols. They provide a way to access and locate resources through identifiers. Component of URI Scheme: Specifies the protocol used to access the resource. Common schemes include http, https, ftp, mailto, and file. Example: http, https. Authority: Includes the domain name (and optionally the port) where the resource is hosted. Format: [user-info@]host[:port] Example: www.example.com, user@host:8080. Path: Specifies the location of the resource on the server. Example: /path/to/resource. Query: Provides additional parameters for accessing the resource. Example: ?key1=value1&key2=value2. Fragment: Indicates a specific part of the resource. Example: #section1. Types of URIs URL (Uniform Resource Locator): A subset of URIs that provides a means of accessing a resource by specifying its primary access mechanism (e.g., location on a network). Example: https://www.example.com/index.html URN (Uniform Resource Name): A subset of URIs that provides a unique name for a resource without implying its location or access mechanism. Example: urn:isbn:978-3-16-148410-0 Uses of URIs Web Browsing: URLs are used to locate web pages and resources. APIs: URIs are used to access endpoints in RESTful APIs. Email: Mailto URIs specify email addresses. File Access: File URIs specify file paths on a local or network file system. Best Creating URIs for RESTful web services involves Practices in following best practices making URI that ensure they are easy to understand, consistent, and for RESTful Web Services meaningful. Here are some key best practices: Best Practices Use Nouns to Represent Resources Use Plural Nouns Hierarchical Resource Structure Use HTTP Methods Appropriately Use Query Parameters for Filtering, Sorting, and Paginatio Use Hyphens to Improve Readability Avoid File Extensions Use Resource Nesting Sparingly Version Your API Use Consistent Resource Names Use Nouns to Represent Resources Resources: URIs should represent resources (nouns) rather than actions (verbs). Example: Use /users instead of /getUsers. Use Plural Nouns Consistency: Use plural nouns for resource names to maintain consistency. Example: /users for a collection of users, /orders for a collection of orders. Hierarchical Resource Structure Relationships: Reflect the hierarchy and relationships between resources in the URI structure. Example: /users/{userId}/orders to represent orders of a specific user. Use HTTP Methods Appropriately CRUD Operations: Map CRUD operations to HTTP methods: GET: Retrieve resources POST: Create new resources PUT: Update existing resources DELETE: Delete resources Example: GET /users to fetch users POST /users to create a new user PUT /users/{userId} to update an existing user DELETE /users/{userId} to delete a user Use Query Parameters for Filtering, Sorting, and Pagination Clarity: Use query parameters to provide additional filtering, sorting, and pagination. Example: /users?sort=desc /orders?page=2&limit=20 /products?category=electronics&price_lt=100 Use Hyphens to Improve Readability Readability: Use hyphens (-) to separate words in URI paths for better readability. Example: /user-profiles instead of /userProfiles. Use Lowercase Letters Consistency: Use lowercase letters in URIs to avoid issues with case sensitivity. Example: /users instead of /Users. Avoid File Extensions Abstraction: Do not include file extensions in URIs to keep them clean and abstract. Example: /users instead of /users.json. Use Resource Nesting Sparingly Depth: Avoid deep nesting of resources to keep URIs short and simple. Example: Instead of /users/{userId}/orders/{orderId}/items, consider /orders/{orderId}/items. Version Your API Versioning: Include the API version in the URI to manage changes and updates. Example: /v1/users, /v2/users. Use Consistent Resource Names Uniformity: Maintain consistency in naming conventions across the API. Example: If using userId in one part of the API, use userId everywhere, not id or user-id. Example URI Do you have any questions? Thank you!!