Restful api design principles

Coding Pricniples

SOLID

  • Five guidelines for writing loosely-coupled code in object-oriented design.
    • Single Responsibility Principle
    • Open Close Principle
    • Liskov substitution Principle
    • Interface Segregation Principle
    • Dependency Inversion Principle

Single Responsibility Principle (SRP)

Concept: A class or module should have only one reason to change, i.e a responsible for a single part of the functionality. (single, well-defined purpose or responsibility).

Benefit: Too often we write a single god class/menthod that does everything, e.g pulling data from api, validating it, connecting to a database, and saving it. These responsibility should be distributed to seperate classes. Changes to one responsibility won't affect others.

Open Close Principle (ocp)

Concept: A software entity (like class, module or function) should be open for extension but closed for modification.

Benefit: Allows you to add new functionality to existing code without altering the original source of code.

Liskov substitution Principle (LSP)

Concept: Also know as "Substitutability". You should be able to use a subclass in place of its parent class. (means you should able to use subclass instance wherever a superclass instance is expected without causing errors.)

Benefit: Ensures that Polymorphism works correctly, making code more reliable and flexible when dealing with Interface.

Interface Segregation Principle (ISP)

Concept: A class should not depend on method that it does not need to implement. (Clients should not forced to depend on interfaces they do not use. Instead of large, general interfaces, it's batter to have multiple small, specific interfaces.)

Benefit: Leads to more focused and decoupled code, as classess only implement the methods that actually need.

Dependency Inversion Principle (DIP)

Concept: High level modules should not depend on low-level modules, both should depend on abstractions i.e. classes and modules should dependent on abstractions instead of concrete implementations(directly).

Benefit: Decouples different part of the system allowing dependencies to be replaced witout changing code aswell as making code more testable allowing depndencies to be easily mocked.


Low of Demeter (LOD)

Concept: Also, principle of least knowlage, a software design guidline promoting loose coupling stating that:

  1. Each unit should have only limited knowlage about othe units, only units "closely" related to the current unit.
  2. Each unit should only talk to its friends, don't talk to strangers.
  3. Only talk to your immediate friends.

Practically, This is low advicees that a method should only call method on itself, it's own field and object passed in as paramenters or object it creates.

Don't Repeat Yourself (DRY)

Keep it Simple (KISS)

You Ain't Gonna Need it (YAGNI)

Restful api design principles

the core principles of REST API design can be broken down into foundational constraints and practical implementation best practices.

Foundational REST Constraints

These are the core architectural principles defined by Roy Fielding that make a service "RESTful":

Client-Server Architecture: The client and server are separate and independent, interacting only through requests and responses. This separation allows each side to evolve independently.

Statelessness: Each request from a client to the server must contain all the information the server needs to fulfill it. The server does not store any client session state between requests, which improves scalability and reliability.

Cacheability: Responses must define themselves as cacheable or non-cacheable (using HTTP headers like Cache-Control). This allows clients or intermediaries to store responses and reuse them, reducing server load and improving performance.

Uniform Interface: The method of communication between client and server is standardized. This is achieved through the use of standard HTTP methods, URIs, and consistent data formats. This is the most crucial constraint.

Layered System: The client cannot tell whether it is connected directly to the end server or to an intermediary (like a load balancer or proxy). This enhances scalability and security. Code on Demand (Optional): The ability for servers to temporarily extend or customize client functionality by transferring executable code (like JavaScript).

Practical API Design Best Practices (C# Context)

When implementing in C# (e.g., with ASP.NET Core Web API), these practices ensure a robust, developer-friendly API:

Resource-Based URIs: Use plural nouns to represent collections of resources (e.g., /api/products), and use path parameters for specific resources (e.g., /api/products/{id}). Avoid using verbs in the URI.

Use Standard HTTP Methods (Verbs): Map CRUD operations to the appropriate HTTP methods:

  • GET: Retrieve a resource or collection (Read). Safe and idempotent.
  • POST: Create a new resource (Create). Not idempotent.
  • PUT: Update or replace an existing resource (Update). Idempotent.
  • PATCH: Perform a partial update to a resource (Update).
  • DELETE: Remove a resource (Delete). Idempotent.

Appropriate HTTP Status Codes: Return standard HTTP status codes to indicate the outcome of the request:

  • 200 OK: Generic success.

  • 201 Created: Resource successfully created (used with POST).

  • 204 No Content: Action successful, but no response body returned (common with PUT, DELETE).

  • 400 Bad Request: Client-side error (e.g., validation failure).

  • 401 Unauthorized: Client is not authenticated.

  • 403 Forbidden: Client is authenticated but lacks permission.

  • 404 Not Found: Resource not found.

  • 500 Internal Server Error: Generic server-side error.

  • Use JSON by Default: Design APIs to accept and return JSON data format, as it is lightweight and widely supported across technologies, including C#.

  • Filtering, Sorting, and Pagination: For large datasets, implement query parameters for filtering, sorting, and pagination (e.g., /api/products?page=1&limit=20) to improve performance and avoid returning excessive data.

Versioning: Plan for API evolution from the start by using a versioning strategy (e.g., URL path versioning like /api/v1/products) to prevent breaking existing clients when changes are introduced.

Security: Always use HTTPS/TLS for secure communication and implement robust authentication (e.g., OAuth, Bearer tokens) and authorization mechanisms to protect resources.

Comments

Popular posts from this blog