Spring Boot 4 Microservices & REST APIs · درس

مبادئ HATEOAS في REST

افهم مبدأ Hypermedia as the Engine of Application State (HATEOAS) وطبّقه على REST APIs الخاصة بك.

الدرس 3 من 311 خطوة

مبادئ HATEOAS في REST درس مجاني في Spring Boot 4 Microservices & REST APIs على CoddyKit. هذا هو الدرس 3 من أصل 3. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Spring Boot 4 Microservices & REST APIs، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Spring Boot 4 Microservices & REST APIs 3 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

HATEOAS Unpacked

HATEOAS stands for Hypermedia as the Engine of Application State. It's a core constraint of RESTful architecture that suggests an API should guide clients through available actions using hypermedia links.

Think of it like a website: you navigate by clicking links, not by typing URLs from memory. HATEOAS brings this same idea to APIs.

Benefits of HATEOAS

HATEOAS makes your API more discoverable and evolvable. Instead of hardcoding URLs, clients discover available actions directly from the API's responses.

  • Client Independence: Clients don't need to know URL structures beforehand.
  • API Evolution: You can change URL paths without breaking clients, as long as the link relation names ("rel") remain consistent.
  • Self-Documentation: Responses inherently describe what actions can be taken next.

Hypermedia as State Engine

The 'Engine of Application State' means that the client transitions between application states (e.g., from viewing a user to viewing their orders) by selecting links within the hypermedia response.

The API response doesn't just return data; it returns data PLUS instructions (links) on what you can do with that data or where you can go next.

Introducing Spring HATEOAS

Implementing HATEOAS manually can be verbose. Thankfully, Spring Boot provides the Spring HATEOAS library to simplify adding links to your REST resources.

It offers classes like EntityModel, CollectionModel, and WebMvcLinkBuilder to make link creation intuitive and robust.

Your First Self-Link

Let's start by adding a 'self' link to a single user resource. This link points back to the resource itself, allowing clients to easily retrieve its current state.

We use EntityModel to wrap our data and WebMvcLinkBuilder to construct the link.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;

@SpringBootApplication
public class SelfLinkApp {
    public static void main(String[] args) {
        SpringApplication.run(SelfLinkApp.class, args);
    }
}

class User {
    private Long id;
    private String name;
    public User(Long id, String name) {
        this.id = id; this.name = name;
    }
    public Long getId() { return id; }
    public String getName() { return name; }
    public void setId(Long id) { this.id = id; }
    public void setName(String name) { this.name = name; }
}

@RestController
class UserController {
    @GetMapping("/users/{id}")
    public EntityModel<User> getUser(@PathVariable Long id) {
        User user = new User(id, "Alice"); // Dummy user
        EntityModel<User> resource = EntityModel.of(user);

        // Add a "self" link
        resource.add(linkTo(methodOn(this.getClass()).getUser(id))
                        .withSelfRel());
        return resource;
    }
}

`EntityModel` & `Link` Deep Dive

When you use Spring HATEOAS, your API responses will typically return objects like EntityModel or CollectionModel.

  • EntityModel<T>: A wrapper for a single domain object (like our User), allowing you to add links to it.
  • Link: Represents a hyperlink, containing a URI and a relation name (e.g., 'self', 'orders').

The client then parses these links to navigate the API.

Linking to Related Resources

Beyond 'self' links, you can add links to related resources. For instance, a user resource might include a link to their orders.

We use withRel("relationName") to define the relationship between the current resource and the linked resource.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;

@SpringBootApplication
public class RelatedLinkApp {
    public static void main(String[] args) {
        SpringApplication.run(RelatedLinkApp.class, args);
    }
}

class User { // Re-using User class
    private Long id; private String name;
    public User(Long id, String name) {
        this.id = id; this.name = name;
    }
    public Long getId() { return id; }
    public String getName() { return name; }
    public void setId(Long id) { this.id = id; }
    public void setName(String name) { this.name = name; }
}

@RestController
class UserController {
    @GetMapping("/users/{id}")
    public EntityModel<User> getUser(@PathVariable Long id) {
        User user = new User(id, "Bob");
        EntityModel<User> resource = EntityModel.of(user);

        resource.add(linkTo(methodOn(this.getClass()).getUser(id))
                        .withSelfRel());
        
        // Add link to user's orders
        resource.add(linkTo(methodOn(this.getClass()).getUserOrders(id))
                        .withRel("orders")); // Define relation
        return resource;
    }

    @GetMapping("/users/{id}/orders")
    public String getUserOrders(@PathVariable Long id) {
        return "Orders for user " + id; // Dummy endpoint
    }
}

`WebMvcLinkBuilder` Magic

WebMvcLinkBuilder is crucial for HATEOAS in Spring. It allows you to create links by directly referencing your controller methods, rather than hardcoding URL strings.

This makes your links type-safe and automatically updates them if you refactor your controller's path or method names, making your API more robust.

HATEOAS for Collections

When returning a list of items, you should use CollectionModel. Each item in the collection can have its own self-link, and the collection itself can have a self-link (e.g., to the list endpoint).

This allows clients to navigate to individual items from a list, or to refresh the entire collection.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.hateoas.CollectionModel;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;
import java.util.Arrays;

import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;

@SpringBootApplication
public class CollectionHateoasApp {
    public static void main(String[] args) {
        SpringApplication.run(CollectionHateoasApp.class, args);
    }
}

class User { // Re-using User class
    private Long id; private String name;
    public User(Long id, String name) {
        this.id = id; this.name = name;
    }
    public Long getId() { return id; }
    public String getName() { return name; }
    public void setId(Long id) { this.id = id; }
    public void setName(String name) { this.name = name; }
}

@RestController
class UserController {
    private List<User> users = Arrays.asList(
        new User(1L, "Charlie"),
        new User(2L, "David")
    );

    @GetMapping("/users")
    public CollectionModel<EntityModel<User>> getAllUsers() {
        List<EntityModel<User>> userResources = users.stream()
            .map(user -> EntityModel.of(user,
                linkTo(methodOn(this.getClass()).getUser(user.getId()))
                    .withSelfRel()))
            .collect(Collectors.toList());

        return CollectionModel.of(userResources,
            linkTo(methodOn(this.getClass()).getAllUsers())
                .withSelfRel()); // Link for the collection
    }

    // Need a getUser method for the link builder to reference
    @GetMapping("/users/{id}")
    public EntityModel<User> getUser(@PathVariable Long id) {
        return EntityModel.of(new User(id, "Dummy"),
            linkTo(methodOn(this.getClass()).getUser(id)).withSelfRel());
    }
}

HATEOAS Quick Check

Which of the following are key benefits of applying HATEOAS principles to a REST API?

HATEOAS Recap & Next

Great job! You've learned about HATEOAS and how it makes REST APIs more discoverable and evolvable by embedding hypermedia links in responses.

  • HATEOAS: Hypermedia as the Engine of Application State.
  • Spring HATEOAS: Provides tools like EntityModel, CollectionModel, and WebMvcLinkBuilder.
  • Links: Guide clients through API interactions, reducing hardcoding.

By applying HATEOAS, you create truly RESTful APIs that are more robust and easier for clients to consume over time.

البدء مجانًا

تعلم Java مع معلم ذكاء اصطناعي — مجانًا

اكتب وقم بتشغيل أكوادك الفعلية في المتصفح، واحصل على مساعدة فورية من معلم ذكاء اصطناعي متاح 24/7، واستمر من حيث توقفت على الويب أو في التطبيق.

الدورات
24
الدروس
93

الأسئلة الشائعة

هل درس «مبادئ HATEOAS في REST» مجاني؟

نعم — نص درس «مبادئ HATEOAS في REST» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Spring Boot 4 Microservices & REST APIs، انتقل إلى CoddyKit PRO. تتضمن دورة Spring Boot 4 Microservices & REST APIs 3 دروس في المجموع.

ماذا ستتعلم في «مبادئ HATEOAS في REST»؟

افهم مبدأ Hypermedia as the Engine of Application State (HATEOAS) وطبّقه على REST APIs الخاصة بك. تتمرن على Spring Boot 4 Microservices & REST APIs مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Spring Boot 4 Microservices & REST APIs؟

لا تُشترط خبرة سابقة. Spring Boot 4 Microservices & REST APIs على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 3 من أصل 3.

كم من الوقت يستغرق درس «مبادئ HATEOAS في REST»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Spring Boot 4 Microservices & REST APIs هذا؟

نعم. كل درس في Spring Boot 4 Microservices & REST APIs يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. التحقق من صحة الطلبات والاستجابات
  2. التقسيم والترتيب
  3. مبادئ HATEOAS في REST
← العودة إلى Spring Boot 4 Microservices & REST APIs