I'm using Django 1.9.6 + Tastypie to implement RESTFUL api, there is an api that need to fetch data from api whitch is on another server, I don't know how to do it.
All the example I'd found is like this:
from tastypie.resources import ModelResource
from services.models import Product
from tastypie.authorization import Authorization
class ProductResource(ModelResource):
class Meta:
queryset = Product.objects.all()
resource_name = 'product'
allowed_methods = ['get']
authorization = Authorization()
The resource class fetch data from app's models(local database), is it possible to request an API which is on another server? If the answer is yes and then how to do it?
Maybe the question is stupid.
Thanks :)
EDITED
One way of implementing it could look like this:
import requests
from requests.exceptions import RequestException
[...]
# implementing connection in models.py gives more flexibility.
class Product(models.Model):
[...]
def get_something(self):
try:
response = requests.get('/api/v1/other/cars/12341')
except RequestException as e:
return {'success': False, 'error': 'Other service unavailable!'}
if response.status_code not in [200, 201, 202, 203, 204, 205]:
return {'success': False, 'error': 'Something went wrong ({}): {}'.format(response.status_code, response.content)}
data = json.load(response.content)
data['success'] = True
return data
def something(self):
self.get_something()
from tastypie.resources import ModelResource
from services.models import Product
from tastypie.authorization import Authorization
class ProductResource(ModelResource):
something = fields.CharField('something', readonly=True)
class Meta:
queryset = Product.objects.all()
resource_name = 'product'
allowed_methods = ['get']
authorization = Authorization()
Note that field wont' be serialized as JSON it's going to be escaped. Find out how to fix it there