JAX-RS RESTful API使用JSON表示和链接资源

时间:2015-07-06 19:49:03

标签: java json rest jax-rs resteasy

有时我会如何混淆RESTful API中的资源链接,例如考虑实体:

个人资料(用户可以创建包含地址,详细信息等的商家资料。)

计划(已在应用程序的数据库中保留,由管理员创建)

创建个人资料的请求如下:

POST /profiles
{
  "name": "Business name",
  "address": "The address",
  "phone": "0000000000" 
}

现在要求个人资料属于定价计划。那么用JSON做这样的POST请求是个好主意吗?

POST /profiles
{
  "name": "Business name",
  "address": "The address",
  "phone": "0000000000"
  "plan": {
    "id": 1
  }
}

然后按提供的 id 加载计划,并将其与正在创建的配置文件相关联:

@POST
@Path("/profiles")
public Response createProfile(Profile profile) {

    // load plan resource from DB
    Plan plan = em.find(Plan.class, profile.getPlan().getId())

    // associate
    profile.setPlan(plan);

    // persist profile
    em.perist(profile);
}

个人资料实体:

@Entity
public class Profile implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(fetch = FetchType.EAGER, optional = false)
    @JoinColumn(name = "plan_id", nullable = false)
    private Plan plan;

    private String name
    ...

    // getters and setters

}

计划实体:

@Entity
public class Plan implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull
    @Column(nullable = false)
    private String name;

    @NotNull
    @Column(nullable = false, columnDefinition = "text")
    private String description;

    @NotNull
    @Column(nullable = false, precision = 8, scale = 2)
    private BigDecimal price;

    @NotNull
    @Column(nullable = false)
    private Integer days;

    @OneToMany(fetch = FetchType.LAZY, mappedBy="plan", cascade = CascadeType.ALL)
    private List<Profile> profiles;

    ...

}

换句话说,我问我应该将什么传递给请求主体以链接引用实体。

我想相信这样的事情更合理:

POST /plans/1/profiles

但根据REST和JSON语义,什么是最佳选择?

我还可以考虑其他方式,例如将计划ID作为查询参数提供:

POST /profiles?planId=1

1 个答案:

答案 0 :(得分:0)

我想说你需要做以下事情:

使用

创建个人资料
POST: /profile

使用

分配计划
PUT: /profile/<profile_id>
{
   "name": <optional>,
   "plan_id": <optional>,
   ...
}

首先,你要分开创建和更新(POST / PUT)。另一个是您在URL中更新状态配置文件ID。

您可以在PUT请求正文中设置需要更新的参数,并仅更新已设置的参数。认为REST概念很好。