Skip to content
Breadcrumb
Resources
GoCardless

gc-http-factory: an easier way to work with APIs in Angular

Jack Franklin
Written by

Last editedJun 2024

Today we're announcing and open sourcing gc-http-factory, a tool for working with APIs in Angular.

Using APIs in Angular without HttpFactory

In a regular Angular app you'd use a service to make requests to an API:

angular.app('app', []).factory('UsersService', function($http) {
  function findOne(id) {
    return $http.get('/api/users/' + id);
  };

  function findAll() {
    return $http.get('/api/users');
  };

  function create() {
    return $http.post('/api/users');
  };

  return {
    findOne: findOne,
    findAll: findAll,
    create: create
  };
});

If you've got lots of API resources which follow similar conventions the above becomes repetitive pretty quickly.

Using HttpFactory

HttpFactory provides an abstraction for creating services that make requests to API resources. You use HttpFactory to create your service and methods by telling it some information about your API.

For example, to create the UsersService we defined previously, you'd use:

angular.app('app', ['gc.httpFactory']).factory('UsersService', function(HttpFactory) {
  return HttpFactory.create({
    url: '/api/users/:id'
  }, {
    findOne: { method: 'GET' },
    findAll: { method: 'GET' },
    create: { method: 'POST' }
  });
});

You can then use the service you've created as normal:

UsersService.findAll(); //=> GET /api/users

UsersService.findOne({
  params: { id: 2 }
}); //=> GET /api/users/2

UsersService.create({
  data: { name: 'Jack' }
}); //=> POST /api/users with { name: 'Jack' } as data

Installation

You can install gc-http-factory from Bower:

bower install gc-http-factory

Or just grab the source from GitHub.

Contributing

We've been using HttpFactory in our Angular apps for a while and we're really happy with how cleanly it lets us create components to interface with our APIs. It's avoided duplication across our Angular apps and we hope it might do the same for you.

If you have any suggestions, ideas or bugs, please either report them on GitHub or feel free to find me on Twitter.

We're hiring developers

See job listing

Over 85,000 businesses use GoCardless to get paid on time. Learn more about how you can improve payment processing at your business today.

Get StartedLearn More

All Categories

PaymentsCash flowOpen BankingFinanceEnterpriseAccountingGoCardlessTechnology
Interested in automating the way you get paid? GoCardless can help
Interested in automating the way you get paid? GoCardless can help

Interested in automating the way you get paid? GoCardless can help

Contact sales