0

I have built an API in laravel. One of the routes it responds to is:

/api/categories/[category_id]

I am working on integrating this with an Angular frontend with a factory so I am doing this:

apiServices.factory('apiService', ['$resource',
  function($resource){
    return $resource('api/categories', {}, {
      'get': {method:'GET', params:{category_id:'@category_id'}, isArray:false}
    });
  }]);

The get method however returns an URL with a query string like this:

/api/categories?category_id=[category_id]

How can I modify it so that it follows Laravel's API and creates and URL like this:

/api/categories/[category_id]

I would prefer to avoid modifying the API to respond to query strings if possible although I could eventually go that route if changing the factory method is too hard.

1 Answer 1

2

This will work. category_id needs to be a route param instead of query parameter.

apiServices.factory('apiService', ['$resource',
function($resource){
return $resource('api/categories/:category_id', {category_id:'@category_id'}, {
  'get': {method:'GET', isArray:false}
});
}]);
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. This will work however the previous implementation allowed me to use the 'query' method against the main URL which returned all categories: apiServices.factory('apiService', ['$resource', function($resource){ return $resource('api/categories', {}, { 'get': {method:'GET', params:{category_id:'@category_id'}, isArray:false}, 'query': {method:'GET', isArray:true}, }); }]); Do you think I should create a separate factory to return all categories and keep the one in your comment to obtain a specific one per category_id?
Acutally it depends on the user interaction. If both the apis are being used on the same page then probably using the query param method is better since single factory serves both all and specific listing. Hence less code. I dont see any benefit it creating a separate per category method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.