Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 25

REST Principles and Resource-Based API Design

Recommended resources

Hello! Welcome to the first lesson of our new module on building APIs.

In the previous module, you mastered the art of managing data within a Django application. You learned how to define data structures with models, manage database schemas with migrations, query the database with the ORM, and even leverage the Django Admin for a ready-made management interface. You've built a solid data foundation.

Now, we pivot from managing data internally to exposing it externally. Modern applications rarely exist in isolation; they communicate with other systems, like mobile apps or single-page web applications. This communication happens through an Application Programming Interface, or API.

This lesson introduces the dominant architectural style for creating these web APIs: REST (Representational State Transfer). Our goal is to explain REST architectural principles and resource-based API design. This is a crucial, foundational lesson that will inform everything we build with the Django REST Framework.

1. What is REST? A High-Level Overview

Before diving into the formal principles, let's get a quick, intuitive understanding of what REST is and why it's so prevalent. At its core, REST is a set of conventions for how clients and servers should communicate over the web.

What Is REST API? Examples And How To Use It: Crash Course System Design #3

To start, let's watch this excellent crash course from ByteByteGo. It provides a concise and clear overview of the fundamental concepts, including what an API is, the definition of REST, and the basic interaction flow.

Watch the video from the beginning up to 03:26. Focus on: The definition of REST as an architectural style, not a strict protocol. The idea of organizing the API around resources (identified by nouns). How HTTP verbs (GET, POST, PUT, DELETE) are used to perform actions on those resources. The role of HTTP status codes in the server's response.

As the video explained, an API that adheres to these conventions is called a "RESTful" API. It's important to understand that REST is not the same as HTTP. Rather, REST is a style that leverages the existing features of the HTTP protocol to create APIs that are predictable, scalable, and easy to understand.


2. The Core of REST: Resource-Based Design

The most fundamental concept in REST is the resource. A resource is an abstraction of information—any "thing" that your application deals with. In your past work with AI projects, a resource could have been a user's resume, a medical appointment, or a specific image to be classified. In a simple e-commerce API, resources would be things like customers, products, and orders.

RESTful design dictates that every resource should have a unique identifier, which is a Uniform Resource Identifier (URI). The design of these URIs is a critical first step.

Designing Resource URIs

A key principle is to use nouns, not verbs, to name your resources. The action to be performed is conveyed by the HTTP method, not the URL.

  • Good: /orders (a collection of orders)
  • Good: /orders/123 (a specific order)
  • Avoid: /createOrder or /getOrderById?id=123

This approach makes the API structure intuitive and predictable. The following article from Microsoft's Azure Architecture Center provides an excellent guide on this topic.

Web API Design Best Practices

Let's dive deeper into how to structure your URIs. This reading provides clear best practices and naming conventions.

Read the section titled 'Define RESTful web API resource URIs'. Pay close attention to the subsections on 'Resource URI naming conventions', especially the guidance on using plural nouns for collections and keeping relationships simple.


3. The Uniform Interface: Interacting with Resources

Once you've defined your resources and their URIs, you need a standard way to interact with them. This is where the Uniform Interface, a cornerstone of REST, comes in. It ensures that clients and servers communicate in a consistent way, regardless of the underlying technology. For web APIs, this is achieved by using standard HTTP methods.

Each HTTP method has a specific, well-defined meaning:

Method Action Example URI
GET Read a resource or collection. /products, /products/42
POST Create a new resource in a collection. /products
PUT Replace/Update an existing resource. /products/42
PATCH Partially update an existing resource. /products/42
DELETE Delete an existing resource. /products/42

This mapping of verbs to CRUD (Create, Read, Update, Delete) operations is central to REST.

Web API Design Best Practices

For a detailed breakdown of each HTTP method, their expected behavior, and the status codes they typically return, let's return to the Azure Best Practices article.

Read the section 'Define RESTful web API methods'. Study the table that summarizes the use of methods on collection vs. individual item resources. Then, read the details for GET, POST, PUT, PATCH, and DELETE requests.

Top 8 Tips For Restful API Design
This infographic provides a great visual summary of the key design principles we've discussed so far, including resource-based paths and the correct use of HTTP methods.
Test your understanding!

Imagine you are designing a REST API for your "AI Career Coach" project. The primary resources are users and resumes. For each scenario below, determine the appropriate HTTP method and URI.

  1. A new user signs up.
  2. A user uploads their resume. Assume a resume is a resource belonging to a user.
  3. A user wants to see a list of all resumes they have uploaded.
  4. A user wants to update their contact information (a field on the users resource) but not change their name.
  5. A user wants to completely replace an old resume with a brand new one.
  6. A user deletes their account.
Show answer
  1. POST /users: Create a new user resource in the users collection.
  2. POST /users/{user_id}/resumes: Create a new resume resource within the collection of resumes belonging to a specific user.
  3. GET /users/{user_id}/resumes: Retrieve the collection of all resumes for a specific user.
  4. PATCH /users/{user_id}: Partially update the user resource. PATCH is ideal because we're only changing some fields.
  5. PUT /resumes/{resume_id}: Completely replace the existing resume resource with the new data provided.
  6. DELETE /users/{user_id}: Delete the specified user resource.

4. The Six Architectural Constraints of REST

So far, we've focused on the most visible aspects of REST. However, for an architecture to be truly RESTful, it must satisfy a set of six guiding constraints defined by Roy Fielding in his dissertation. Your desire to understand the "under the hood" aspects of systems makes this formal definition particularly relevant.

REST API - REST Constraints

This video from TutorialsPoint systematically explains each of the six architectural constraints that define REST.

Watch the entire video (around 13 minutes). It will walk you through each of the six constraints. I will provide a summary of each point below for you to review.

Here is a summary of the six constraints covered in the video:

  1. Client-Server Architecture: This enforces a separation of concerns. The client (e.g., a web browser or mobile app) is concerned with the user interface, while the server is concerned with data storage and business logic. They evolve independently, communicating only through the API. This is the fundamental model of the web.

  2. Statelessness: This is a critical constraint. The server does not store any information about the client's session between requests. Every request from a client must contain all the information needed to understand and process it. This makes the system highly scalable, as any server can handle any request.

  3. Cacheability: Responses from the server should indicate whether they are cacheable or not. If a response is cacheable, the client is allowed to reuse that data for subsequent requests, which improves performance and reduces network traffic.

  4. Layered System: The architecture can be composed of multiple layers (e.g., load balancers, proxies, gateways). A client connects to an endpoint but has no knowledge of whether it's talking directly to the application server or to an intermediary. This allows for flexibility in the system architecture.

  5. Code on Demand (Optional): This is the only optional constraint. It allows the server to temporarily extend the client's functionality by sending executable code (e.g., JavaScript). This is how modern single-page applications work.

  6. Uniform Interface: This is the principle that distinguishes REST from other architectural styles. It's so important that it has its own four sub-constraints:

    • Identification of Resources: Using URIs to identify resources (which we've covered).
    • Manipulation of Resources Through Representations: The client interacts with a representation of the resource (like a JSON object), not the resource itself.
    • Self-Descriptive Messages: Each message contains enough information for the receiver to process it. HTTP headers like Content-Type (e.g., application/json) and the HTTP methods themselves achieve this.
    • Hypermedia as the Engine of Application State (HATEOAS): This is the most mature and often least implemented principle. It states that a client should be able to navigate the API entirely by following links provided in the server's responses, rather than hardcoding URIs. For example, when you fetch a user, the response should contain a link to fetch that user's orders.
Venn Diagram of REST Architectural Principles
This diagram helps visualize the relationship between basic HTTP-based APIs, the core principles of REST, and the advanced HATEOAS principle. A truly RESTful API incorporates all these elements.

5. The Richardson Maturity Model

Not all APIs that call themselves "RESTful" fully adhere to these principles, especially HATEOAS. The Richardson Maturity Model provides a useful way to think about this, grading APIs on a scale from Level 0 to Level 3.

Web API Design Best Practices

To wrap up our theoretical exploration, read this short section of the Azure article. It introduces a model for evaluating how 'RESTful' an API truly is.

Read the section 'Web API maturity model'. This will help you classify APIs based on their adherence to the principles we've discussed.

  • Level 0: Using HTTP as a transport system, but without leveraging any of its mechanisms for resources or verbs.
  • Level 1: Using distinct URIs for different resources.
  • Level 2: Using HTTP verbs to perform actions on resources. Most public "REST" APIs operate at this level.
  • Level 3: Incorporating hypermedia (HATEOAS), achieving a truly RESTful system.

Conclusion

This lesson provided a comprehensive theoretical foundation for REST. You've moved from a high-level overview to a deep dive into the specific constraints and design patterns that define a RESTful architecture.

Key Takeaways:

  • REST is an architectural style, not a protocol, that provides a set of conventions for building scalable and maintainable web APIs.
  • Resource-Based Design is central to REST. APIs are organized around resources (nouns) identified by unique URIs.
  • The Uniform Interface, primarily through standard HTTP methods (GET, POST, PUT, PATCH, DELETE), provides a consistent way to interact with resources.
  • A truly RESTful API adheres to six architectural constraints: Client-Server, Stateless, Cacheable, Layered System, Uniform Interface, and optionally Code on Demand.
  • HATEOAS is the principle of including navigational links within API responses, allowing clients to discover actions and resources dynamically.

Preview of the Next Lesson:
With this theoretical groundwork in place, we are ready to get practical. In the next lesson, you will install and configure the Django REST Framework (DRF) in your Django project. DRF is a powerful toolkit that makes it easy to build RESTful APIs that follow the principles you've learned today.