Complete AngularJS guide for REST API operations: GET, POST, PUT, DELETE

Hey everyone,

I’m working on an AngularJS app that needs to talk to a RESTful backend. I’ve got most of it working, but I’m stuck on the PUT method. Here’s what I’ve done so far:

angular.module('userServices', ['ngResource']).
    factory('Users', function($resource){
    return $resource('http://api.example.com/users/:userId', {}, {
      fetchAll: {method:'GET', params:{userId:''}, isArray:true},
      create: {method:'POST'},
      modify: {method:'PUT'},
      erase: {method:'DELETE'}
    });

The GET, POST, and DELETE operations work fine. But when I try to update a user with PUT, the URL doesn’t include the user ID. It’s just /users instead of /users/123.

I’ve tried a few workarounds, but nothing seems to work. Does anyone have a good example of how to implement all four CRUD operations correctly in AngularJS? I’ve heard about Restangular, but I’m not sure if that’s the way to go.

Any help would be awesome. Thanks!

yo, good question! have u tried $http.put? it gives u more control: $http.put(‘http://api.example.com/users/’ + userId, userData).then(res => { /* success */}); might work better than resource. hope it helps, lmk if issues.

I’ve encountered similar issues with AngularJS and REST APIs. One approach that worked well for me was using a custom interceptor to handle the URL transformation for PUT requests. You can set this up in your app’s config:

app.config(['$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push(function() {
        return {
            request: function(config) {
                if (config.method === 'PUT' && config.url.indexOf('/users') > -1) {
                    config.url = config.url.replace('/users', '/users/' + config.data.id);
                }
                return config;
            }
        };
    });
}]);

This way, you don’t need to modify your resource definition. It automatically adds the user ID to PUT requests, solving the URL issue you’re experiencing.

hey there! i’m curious, have you tried adding the userId to your PUT request? something like:

modify: {method:'PUT', params:{userId:'@id'}}

this should include the user ID in the URL. also, what kinda data are you sending in the PUT request? maybe there’s an issue with the payload? lemme know if you need more help!