IT story

리소스에 대한 ID 배열을 사용하는 REST API를 구성하는 방법

hot-time 2020. 9. 7. 21:24
반응형

리소스에 대한 ID 배열을 사용하는 REST API를 구성하는 방법


내 프로젝트를위한 REST API를 구축하고 있습니다. 주어진 사용자의 정보를 얻기위한 API는 다음과 같습니다.

api.com/users/[USER-ID]

또한 클라이언트가 사용자 ID 목록을 전달하도록 허용하고 싶습니다. RESTful이되고 사용자 ID 목록을 가져 오도록 API를 어떻게 구성 할 수 있습니까?


URL의 모든 매개 변수를 전달하는 경우 쉼표로 구분 된 값이 최선의 선택 일 것입니다. 그러면 다음과 같은 URL 템플릿이 생깁니다.

api.com/users?id=id1,id2,id3,id4,id5

 api.com/users?id=id1,id2,id3,id4,id5
 api.com/users?ids[]=id1&ids[]=id2&ids[]=id3&ids[]=id4&ids[]=id5

IMO, 위의 호출은 RESTful로 보이지 않지만 빠르고 효율적인 해결 방법입니다 (y). 그러나 URL의 길이는 웹 서버에 의해 제한됩니다 (예 : tomcat) .

RESTful 시도 :

POST http://example.com/api/batchtask

   [
    {
      method : "GET",
      headers : [..],
      url : "/users/id1"
    },
    {
      method : "GET",
      headers : [..],
      url : "/users/id2"
    }
   ]

서버는 새로 생성 된 배치 작업 리소스의 URI를 회신 합니다.

201 Created
Location: "http://example.com/api/batchtask/1254"

이제 클라이언트는 폴링을 통해 배치 응답 또는 작업 진행률을 가져올 수 있습니다.

GET http://example.com/api/batchtask/1254


다른 사람들 이이 문제를 해결 하려고 시도한 방법입니다 .


을 사용하여 동일한 작업을 수행하는 다른 방법을 찾습니다 @PathParam. 다음은 코드 샘플입니다.

@GET
@Path("data/xml/{Ids}")
@Produces("application/xml")
public Object getData(@PathParam("zrssIds") String Ids)
{
  System.out.println("zrssIds = " + Ids);
  //Here you need to use String tokenizer to make the array from the string.
}

다음 URL을 사용하여 서비스를 호출하십시오.

http://localhost:8080/MyServices/resources/cm/data/xml/12,13,56,76

어디

http://localhost:8080/[War File Name]/[Servlet Mapping]/[Class Path]/data/xml/12,13,56,76

이 접근 방식을 선호하는만큼 :-

    api.com/users?id=id1,id2,id3,id4,id5

올바른 방법은

    api.com/users?ids[]=id1&ids[]=id2&ids[]=id3&ids[]=id4&ids[]=id5

또는

    api.com/users?ids=id1&ids=id2&ids=id3&ids=id4&ids=id5

이것이 이하는 방법 입니다. 이것이 PHP가하는 방법 입니다. 이것이 노드가하는 방법입니다 ...


ASP.NET MVC를 사용하여 Rest API 또는 편안한 프로젝트를 빌드하고 데이터를 JSON으로 반환 할 수 있습니다. 컨트롤러 기능의 예는 다음과 같습니다.

        public JsonpResult GetUsers(string userIds)
        {
           var values = JsonConvert.DeserializeObject<List<int>>(userIds);

            var users = _userRepository.GetAllUsersByIds(userIds);

            var collection = users.Select(user => new { id = user.Id, fullname = user.FirstName +" "+ user.LastName });
            var result = new { users = collection };

            return this.Jsonp(result);
        }
        public IQueryable<User> GetAllUsersByIds(List<int> ids)
        {
            return _db.Users.Where(c=> ids.Contains(c.Id));
        }

Then you just call the GetUsers function via a regular AJAX function supplying the array of Ids(in this case I am using jQuery stringify to send the array as string and dematerialize it back in the controller but you can just send the array of ints and receive it as an array of int's in the controller). I've build an entire Restful API using ASP.NET MVC that returns the data as cross domain json and that can be used from any app. That of course if you can use ASP.NET MVC.

function GetUsers()
    {
           var link = '<%= ResolveUrl("~")%>users?callback=?';
           var userIds = [];
            $('#multiselect :selected').each(function (i, selected) {
                userIds[i] = $(selected).val();
            });

            $.ajax({
                url: link,
                traditional: true,
                data: { 'userIds': JSON.stringify(userIds) },
                dataType: "jsonp",
                jsonpCallback: "refreshUsers"
            });
    }

참고URL : https://stackoverflow.com/questions/4541338/how-to-construct-a-rest-api-that-takes-an-array-of-ids-for-the-resources

반응형