简体   繁体   中英

What is the best practise in spring rest for coding Id based and name based API

Let us consider the below API.

/school/{schoolId or schoolName}
/school/{schoolId or schoolName}/students/{studentId or studentName}

I have to develop the above API's. What is the best way to achieve this in spring REST ? I can simply get the URL path variable as a string and check whether it is an id or name and then process it.

But is there any other better solution for this?

There is an elephant in the room, School Name or Student Name is not unique. So it is not advisable to use it in place of id, else you will burn your hand.

  1. /school/{schoolId or schoolName}

I would split this into 2 end points

1. /school s /{schoolId}

if found , return the school entity

HTTP-200
{
  "id" : "id-123",
  "name" : "worlds best school ever",
  "address" : "123 somestreet, some city, some state"
} 

if not found ,

HTTP 404 and an empty body

2. /school s ?name="worlds best school" (other optional things, like sort by, pagination etc)

if at least one entity found per search criteria

HTTP-200
[
    {
      "id" : "id-123",
      "name" : "worlds best school ever",
      "address" : "123 somestreet, some city, some state"
    }
]

If NO entity found per search criteria

HTTP-200
[]
  1. /school/{schoolId or schoolName}/students/{studentId or studentName}

This begs a question, does one student belong to more than one school, I don't think so. If that's the case, /school/{schoolId or schoolName} is an unnecessary/redundant information. If so, I would change it as

1. /student s /{studentId}

if found

HTTP-200
{
  "id" : "studentid-345",
  "name" : "Albert Einstein",
  "school_id" : "id-123"
} 

if not found

HTTP 404 with empty body

2. /student s ?name="Albert Einstein" (other optional things, like sort by, pagination etc)

If at least one entity found per search criteria

HTTP-200
[
    {
      "id" : "studentid-345",
      "name" : "Albert Einstein",
      "school_id" : "id-123"
    }
]

If NO entity found per search criteria

HTTP-200
[]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM