Skip to content

Latest commit

 

History

History
709 lines (486 loc) · 23.8 KB

File metadata and controls

709 lines (486 loc) · 23.8 KB

Lecture 101 - Introduction to API Design

REST API Design

Outline

  1. Introduction to REST API

    1. Overview of REST principles
    2. Benefits of REST architecture
    3. Key concepts (resources, representations, stateless communication)

  2. HTTP Basics

    1. Understanding HTTP methods (GET, POST, PUT, PATCH, DELETE)
    2. Status codes and their meanings
    3. Request and response headers
    4. URI (Uniform Resource Identifier) structure

  3. Designing Resources

    1. Identifying resources and their relationships
    2. Resource naming conventions (URL structure)
    3. Versioning resources
    4. Resource representations (JSON, XML etc.)

Introduction to REST API

REST stands for Representational State Transfer. It is a set of architectural principles for designing web services. RESTful APIs are designed to be easy to use, scalable, and maintainable.

The six REST principles are:

  1. Uniform Interface

    The uniform interface principle states that all resources should be accessed using the same HTTP methods (GET, POST, PUT, PATCH, DELETE). This makes it easy for clients to learn how to use the API.

    For example - To get a list of all users, a client would use the GET method on the URL "/users". To create a new user, a client would use the POST method on the URL "/users". To update an existing user, a client would use the PUT method on the URL "/users/123". To delete an existing user, a client would use the DELETE method on the URL "/users/123".

  2. Client-Server

    The client-server principle states that the client and server should be independent of each other. This means that the client should not need to know anything about the server’s implementation in order to use the API.

    For example - A client that uses a RESTful API to get a list of users should not need to know how the server stores the users' data. The client should only need to know the URL of the resource (in this case, "/users").

  3. Statelessness

    The statelessness principle states that each request from the client should be independent of the previous requests. This means that the server does not need to maintain any state information about the client.

    For example - A client that uses a RESTful API to get a list of users should not need to provide any authentication information. The server should be able to return the list of users without knowing anything about the client.

  4. Cacheability

    The cacheability principle states that resources can be cached by the client or by intermediary systems. This can improve performance by reducing the number of request that need to b made to the server.

    For example - A client that uses a RESTful API to get a list of users can cache the list of users. This means that the client does not need to make a requests to the server every time it need to get a list of users.

  5. Layered System

    The layered system principle states that the API can be implemented as a layered system. This means that the API can be divided into different layers, each of which can be implemented independently.

    For example - A RESTful API for a social media application could be implemented as a layered system. The first layer could handle authentication and authorization. The second layer could handle resource management. The third layer could handle data access.

  6. Code on Demand

    The code on demand principle states that the API can be used to download executable code. This can be useful for extending the client's functionality.

    For example - A RESTful API for a game could be used to download new levels or characters. This would allow the client to be updated without having to download the entire game again.


Step-by-step Guidelines

Here are some step-by-step guidelines for designing a RESTful API:

  1. Identify the resources. The first step is to identify the resources that will be exposed by the API. A resource can be anything that can be named, such as a user, a product, or an order.

  2. Determine the HTTP methods. The next step is to determine the HTTP methods that will be used to access the resources. The most common HTTP methods are GET, POST, PUT, PATCH and DELETE.

  3. Create URLs for the resources. Each resource should have a unique URL. URIs should be consistent and easy to remember.

  4. Define the payloads. The payload is the data that is sent to the server or returned from the server. The payload format should be consistent for all resources.

  5. Test the API. Once the API is designed, it should be tested to make sure that it works as expected.

Example

Here are some examples of RESTful APIs:

  • The GitHub API allows developers to access information about GitHub repositories.

  • The Twitter API allows users to access information about tweets.

  • The Google Maps API allows developers to access information about maps and directions.


Key Components of a REST API

  1. Resources:

    • Resources represent the key entities or objects in your system that are exposed through the API.

    • Each resource should have a unique identifier (URI) and can have multiple representations.

  2. URI (Uniform Resource Identifier):

    • URIs are used to uniquely identify and address resources in a RESTful API.

    • URIs follow a hierarchical structure, allowing clients to navigate and interact with resources.

  3. HTTP Methods (Verbs):

    • HTTP methods define the actions that can be performed on resources.

    • Commonly used methods in RESTful APIs include GET, POST, PUT, PATCH and DELETE.

  4. Headers:

    • Headers contain additional metadata and instructions for the server and client.

    • Headers can include information like authentication credentials, content type, caching instructions, etc.

  5. Request and Response:

    • Requests are made by clients to perform actions on resources.

    • Responses are sent by the server in response to client requests and contain the result or status of the operation.

  6. Representation:

    • Representations define how resources are structured and presented in requests and responses.

    • Representations can be in various formats such as JSON, XML, HTML, or binary data.

  7. Status Codes:

    • HTTP status codes indicate the outcome of a client's request.

    • Common status codes include 200 (OK), 201 (Created), 400 (Bad Request), 404 (Not Found), 500 (Internal Server Error), etc.

  8. Parameters:

    • Parameters allow clients to provide additional data or instructions to the server.

    • Parameters can be included in the URL (query parameters) or the request body (form parameters or request payload).

  9. Authentication and Authorization:

    • Authentication ensures that the client is a valid and authorized user of the API.

    • Authorization defines what actions a user is allowed to perform on resources based on their role or permissions.

  10. Error Handling:

    • APIs should have proper error handling mechanisms to provide meaningful error responses in case of failures or invalid requests.

    • Error responses should include appropriate status codes, error messages, and possibly error details or codes.

  11. Pagination and Filtering:

    • For resources with large datasets, APIs often provide mechanisms for pagination to retrieve data in chunks.

    • Filtering allows clients to request a subset of resources based on specific criteria or parameters.

  12. Versioning:

    • Versioning allows APIs to evolve over time without breaking existing client integrations.

    • APIs can be versioned using URL path, query parameters, or custom headers.

  13. Hypermedia:

    • Hypermedia, often referred to as HATEOAS (Hypermedia as the Engine of Application State), enables the API to include links to related resources in responses.

    • Clients can dynamically navigate the API by following these hypermedia links.


Benefits of REST Architecture:

  1. Scalability and Performance:

    • RESTful APIs are stateless, allowing them to handle a large number of concurrent requests efficiently.

    • Load balancing techniques can be applied to distribute traffic across multiple servers, improving scalability.

    • Caching mechanisms can be employed to reduce server load and enhance performance.

  2. Simplicity and Ease of Use:

    • REST leverages familiar HTTP protocols and methods making it easy for developers to understand and use.

    • It has a lightweight and intuitive design, which promotes simplicity in API development.

    • RESTful APIs can be accessed using standard web technologies and tools.

  3. Flexibility and Modifiability:

    • REST allows for loose coupling between the client and server, enabling independent evolution of both.

    • It facilitates the addition, modification, or removal of resources without impacting existing clients.

    • Changes in representations and business logic can be implemented without affecting the API interface.

  4. Compatibility and Interoperability:

    • RESTful APIs are platform-independent, enabling communication between heterogeneous systems.

    • They can be consumed by a variety of clients, including web browsers, mobile apps and other services.

    • REST promotes the use of standard data formats like JSON and XML, enhancing interoperability.

  5. Security and Reliability:

    • REST supports various security mechanisms, such as SSL/TLS encryption and token-based authentication.

    • It integrates well with existing security infrastructures, providing robust security measures.

    • RESTful APIs are designed to be reliable, with built-in mechanisms for error handling and retying.

HTTP Basics

HTTP Methods and their usages:

HTTP Method Usage
GET Retrieve a representation of a resource or a resource collection
POST Create a new resource or perform a specific action
PUT Replace an entire resource with a new representation
PATCH Update a specific part of a resource
DELETE Delete a resource or a resource collection
HEAD Retrieve the headers of a resource without the body
OPTIONS Retrieve the available methods and options for a resource

HTTP Status Code and their usages:

HTTP Status Code Usage
200 OK - The request was successful and the response contains data
201 Created - A new resource was successfully created
204 No Content - The request was successful, but there is no data
304 Not Modified - The requested resource has not been modified
400 Bad Request - The request is malformed or has invalid data
401 Unauthorized - Authentication is required for the request
403 Forbidden - The server understood the request, but refused it
404 Not Found - The requested resource does not exist
405 Method Not Allowed - The requested method is not allowed
500 Internal Server Error - An unexpected error occurred
503 Service Unavailable - The server is currently unavailable

More


Request Header and their usages:

Request Header Usage
Accept Specifies the desired response content type
Authorization Provides credentials for authentication
Content-Type Specifies the media type of the request payload
Content-Length Indicates the length of the request payload
User-Agent Identifies the user agent making the request
Cache-Control Specifies caching directives for the request and response
Cookie Includes previously stored cookies for server identification
If-Match Performs conditional requests based on the entity's current state
If-None-Match Performs conditional requests based on the entity's current state
If-Modified-Since Performs conditional requests based on the entity's last modified date
Referer Indicates the URl of the referring resource
Host Specifies the target host and port for the request

Response Header and their usages:

Content-Type Specifies the media type of the response payload
Content-Length Indicates the length of the response payload
Cache-Control Specifies caching directives for the response
ETag Provides an entity tag for versioning and caching
Last-Modified Indicates the last modified date of the response content
Location Specified the URL for redirection or newly created resources
Access-Control-Allow-Origin Defines the allowed origins for cross-origin resource sharing
Set-Cookie Sets a cookie in the client's browser for session management
Expires Specifies the expiration date/time of the response
WWW-Authenticate Challenges the client to provide authentication credentials
Server Identifies the server software/version in the response
X-Powered-By Indicates the technology or framework powering the server

Custom Request Headers:

  1. X-Api-Key: Used to send a API key for authentication or authorization purposes.
    Example: X-Api-Key: YOUR_API_KEY

  2. X-Custom-Header: Used to include additional custom metadata in the request.
    Example: X-Custom-Header: SomeValue

  3. X-Requested-With: Indicates the type of request (e.g., XMLHttpRequest) made by the client.
    Example: X-Requested-With: XMLHttpRequest

Custom Response Headers:

  1. X-RateLimit-Limit: Indicates the maximum number of requests a client is allowed within a given time frame.
    Example: X-RateLimit-Limit: 1000

  2. X-RateLimit-Remaining: Indicates the number of remaining requests the client can make within the current time frame.
    Example: X-RateLimit-Remaining: 500

  3. X-Custom-Header: Used to include additional custom metadata in the response.
    Example: X-Custom-Header: SomeValue

  4. Access-Control-Expose-Headers: Specifies which custom headers can be accessed by the client in cross-origin resource sharing (CORS) scenarios.
    Example: Access-Control-Expose-Headers: X-Custom-Header


Structure of the URI (Uniform Resource Identifier)

The structure of a URI (Uniform Resource Identifier) consists of several components that help identify and locate a resource. A URI can be divided into the following parts:

  1. Scheme:

    • The scheme indicates the protocol or mechanism used to access the resource.

    • Examples: "http://", "https://", "ftp://", "file://", "milto:"

  2. Authority:

    • The authority portion identifies the server or network location where the resource resides.

    • It typically includes the hostname and, optionally, the port number.

    • Example: "example.com", "api.example.com:8080"

  3. Path:

    • The path specifies the hierarchical structure or path to the resource on the server.

    • It typically includes the hostname and, optionally, the port number.

    • Example: "/users", "/products/123", "/files/documents/report.pdf"

  4. Query Parameters:

    • Query parameters provide additional information to the server for processing the request.

    • They are appended to the URi after a question mark (?) and separated by ampersands (&).

    • Example: "/search?q=keyword&page=1&limit=10".

  5. Fragment:

    • The fragment identifier refers to a specific part or section within the resource.

    • It is preceded by a hash symbol (#) and is commonly used in web pages to navigate to specific sections.

    • Example: "/document.pdf#page=3", "/article.html#section-2".

  • Example URL: "https://api.example.com/users?role=admin#section-profile"

Designing Resources

Designing resources in a REST API involves identifying the key entities or objects in your system and representing them in a structured and intuitive manner. Here's a step-by-step guide on how to design resources in a REST API with examples:

  1. Identify Key Entities:

    • Determine the core entities or objects in your system that you want to expose through the API.

    • Examples: Users, products, orders, blog posts.

  2. Determine Resource Relationships:

    • Identify the relationships and associations between the entities.

    • Determine how these relationships can be represented in the API.

    • Examples: A user can have multiple orders, a product can belong to a category.

  3. Define Resource URIs:

    • Choose clear and meaningful names for your resources that reflect their purpose.

    • Use nouns or noun phrases to represent resources.

    • Examples: User, Product, Order.

  4. Design Resource URIs:

    • Assign a unique URI (Uniform Resource Identifier) to each resource.

    • The URI should reflect the hierarchy and organization of the resources.

    • Examples:

      • Users: "/users"
      • User with ID 123: "/users/123"
      • Products: "/products"
      • Products with ID 456: "/products/456"
      • GET /users
      • POST /users
      • GET /users/{id}
      • PUT /users/{id}
      • PATCH /users/{id}
      • DELETE /users/{id}
      • GET /users/{id}/profile
      • GET /users/{id}/experiences
      • GET /users/{id}/experiences/{eid}
      • PUT /users/{id}/experiences/{eid}
      • GET /experiences/{id}/users/{uid}

  1. Determine Resource Representations:

    • Decide on the structure and format of the resource representations.

    • Use commonly accepted formats like JSON or XML.

    • Include relevant attributes and relationships in the representations.

    • Examples:

      • JSON representation of a user:

        {
           "id": 123,
           "name": "John doe",
           "email": "[email protected]"
        }
        
      • JSON representation of a product:

        {
           "id": 456,
           "name": "Widget",
           "price": 9.99,
           "category": "Electronics"
        }
        

  1. Define CRUD Operations:

    • Determine the CRUD (Create, REad, Update, Delete) operations that can be performed on each resource.

    • Map these operations to appropriate HTTP methods.

    • Examples:

      • Create an user: POST /user
      • Retrieve an user: GET /users/123
      • Update an user: PUT /users/123
      • Delete an user: DELETE /users/123

  1. Consider Resource Collections:

    • If your resource represents a collection of items, consider providing endpoints to retrieve and manipulate the collection as a whole.

    • Examples:

      • Retrieve all users: GET /users
      • Create multiple products: POST /products

  1. Handle Resource Relationships:

    • If your resources have relationships, design the URI structure and actions to manage these relationships.

    • Provide mechanisms to navigate and access related resources.

    • Examples:

      • Retrieve orders for a user: GET /users/123/orders

      • Add a product to a user's favorites: POST /users/123/favorites


Resource Naming Conventions & Versioning

Resource naming conventions, specifically the URL structure, play a crucial role in designing a REST API. Here are some commonly followed conventions and best practices for naming resources in a REST API:

  1. Use Nouns to Represent Resources:

    • Choose nouns or noun phrases to represent resources in the URL.

    • Avoid verbs or actions in the URL as the HTTP method indicates the action.

    • Examples:

      • /users instead of /getUsers
      • /products instead of /retrieveProducts

  1. Use Plural Nouns for Resource Collections:

    • Use plural nouns to represent collections of resources.

    • Collections typically represent multiple instances of a resource.

    • Example:

      • /users for a collection of user resources
      • /products for a collection of product resources.

  1. Use Singular Nouns for Individual Resources:

    • Use singular nouns to represent individual resources within a collection.

    • Each individual resource is identified by a unique identifier.

    • Examples:

      • /users/123 for a specific user with ID 123
      • /products/456 for a specific product with ID 456

  1. Use Hierarchical Structure for Related Resources:

    • Use a hierarchical structure to represent relationships between resources.

    • Place related resources as sub-resources under their parent resources.

    • Examples:

      • /users/123/orders for orders belonging to user with ID 123
      • /categories/789/products for products belonging to category with ID 789

  1. Avoid Deep Nesting in URL Structure:

    • Limit the depth of nesting in the URL structure to keep it simple and maintainable.
    • Excessive nesting can lead to long and complex URLs.
    • Consider flattening the structure or using query parameters for complex filtering or searching operations.

  1. Use Hyphens or Underscores for Readability:

    • Use hyphens (-) or underscores (_) to separates words in the URL for readability.

    • Choose one convention and be consistent throughout the API.

    • Examples:

      • /product-reviews or product_reviews for reviews associated with products

  1. Avoid Using File Extensions:

    • Avoid including file extensions (e.g., .html, .json) in the URL for resources.
    • Instead, rely on content negotiation using the Accept header to specify the desired representation format.

  1. Versioning:

    • Consider including versioning information in the URL to manage API changes and backward compatibility.

    • Examples:

      • /v1/users for version 1 of the users resource
      • /v2/users for version 2 of the users resource