tomsv
tomsv

Reputation: 7277

Generate API client from Django REST framework API

I have an website in Django that is using the REST framework to provide an API.

Is there a way to generate an API client that can be used to communicate with this API that provides objects mapping the contents of the API?

Upvotes: 1

Views: 463

Answers (1)

Ross Rogers
Ross Rogers

Reputation: 24240

If you're talking about a javascript client API, I have a django management task that I use to generate a javascript library from my DRF API using AngularJS 1.*. I'm still using DRF 2.4, for easy nested object writes, and Django 1.7. Here it is as a github gist

Take that file, stick it in <app>/management/commands/ and call it like:

python manage.py rest_framework_2_js rest_api.gen.js [base_factory_name] [server_base_url]

If your base_factory_name was foo and you had an API object at server_base_url/Bar/ named Bar, you would use it like:

foo.Bar.get(42)
  .then(function(bar_inst) { 
     console.log(bar_inst);
     bar_inst.baz = 77;
     bar_inst.save()
       .then(function() {
         console.log('bar_inst has been saved');
       });
  })

or

foo.BarList.get('filter_a=5&field_filter_b=abc,d')
  .then(function(data) {
    console.log(data.results);
  })

Each instance in the data.result will be a foo.Bar instance.

You can add callbacks before sending to the server and after retrieving from the server using foo.Bar.pre_save(function (inst) {/*callback mutator*/}) and foo.Bar.post_restore( function(inst) { /*callback mutator*/}).

Anyways, this management task is not productized and it has only one user - me, but I have been using it for 2 years and it works great for me :-) We can work to get it working in your configuration if you like. Naturally the biggest caveat is the AngularJS 1.* dependency.

Upvotes: 1

Related Questions