Code Monkey home page Code Monkey logo

django-oscar-api's Introduction

Django Oscar API

This package provides a RESTful API for django-oscar.

https://travis-ci.org/django-oscar/django-oscar-api.svg?branch=master Coverage Documentation Status Latest PyPi release

Usage

To use the Oscar API application in an Oscar E-commerce site, follow these steps:

  1. Install the django-oscar-api package (pip install django-oscar-api).

  2. Add rest_framework and oscarapi to INSTALLED_APPS

    INSTALLED_APPS = [
     ...
     'rest_framework',
     'oscarapi',
    ]
  3. Add the application's urls to your urlconf

    from django.urls import include
    
    urlpatterns = (
        # all the things you already have
        path("api/", include("oscarapi.urls")),
    )
  4. Apply migrations:

    python manage.py migrate
    

See the Documentation for more information and the Changelog for release notes.

django-oscar-api's People

Contributors

akutsuacts avatar albertojacini avatar aleksandrpanteleymonov avatar andriilahuta avatar bufke avatar carxwol avatar codeinthehole avatar crgwbr avatar farooqaaa avatar fquinner avatar maerteijn avatar maiksprenger avatar michaelkuty avatar mmazur-work avatar nakarinh14 avatar patil2099 avatar pimvernooij avatar raghavdasila avatar randommaker avatar richlloydmiles avatar salahaddin avatar samar-hassan avatar samitnuk avatar snake-soft avatar solarissmoke avatar specialunderwear avatar taaviteska avatar viggo-devries avatar whyscream avatar woutdp avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-oscar-api's Issues

Api Gateway and Authorizations

Hello , i am new using Django Oscar Api .I am using the latest stable version :1.0.10 (2016-12-08)

I just installed and need to use Api Key resource protection.I just create an Api Key Object in the Admin Panel, add to settings.py oscarapi.middleware.ApiGatewayMiddleWare and every time i send a request to : GET localhost:8000/api/ with the Header HTTP_AUTHORIZATION : Authorization:2W1bqko79ZF3Vit038e610R6DXIvkkyB it says that i dont have a permission.So do i need to add some class permission or is just bad configuration?

Oscar api for basket does not show **Shipping Discount** in Offer Discounts:

I have been using oscar api for mobile app. I need to show some shipping discounts in the basket api. Like If I apply conditional offer (free shipping above 250 USD). How can I show it to mobile user.

I have made /api/basket/shipping-methods/ api which loads shipping cost and discount for the current user basket. It shows the discounts on matching condition but how will I show the user that what condition we have applied for free shipping cost. Free shipping above what amount in the basket? So this condition value will be dynamic so I need to show it to the user.

For now it does not show that shipping discounts, I need to show the title of the shipping discount. Kindly suggest me some solution to figure it out.

Question about implementing an express checkout api

Hi There,

I need an api that is essentially a single product express checkout, so to speak. I've developed a view that is a combination of the basket.addproductview and checkoutview. I'm new to Django/oscar (recovering C# developer) and I'd like to know if this is the right approach for such a feature. Thanks in advance.

    def post(self, request, format=None):
        # deserialize the product from json
        p_ser = self.add_product_serializer_class(
            data=request.data['addproduct'], context={'request': request})
        if p_ser.is_valid():
            # create a basket
            basket = operations.get_basket(request)
            # load the validate the product
            product = p_ser.validated_data['url']
            # load the validated quantity
            quantity = p_ser.validated_data['quantity']
            # load any options
            options = p_ser.validated_data.get('options', [])
            #validate the basket
            basket_valid, message = self.validate(
                basket, product, quantity, options)
            if not basket_valid:
                return Response(
                    {'reason': message},
                    status=status.HTTP_406_NOT_ACCEPTABLE)

            # add the product to the validated basket
            basket.add_product(product, quantity=quantity, options=options)

            # apply offers
            operations.apply_offers(request, basket)
            ###### from oscarapi.views.checkout
            # deserialize the checkout object and complete the order
            co_data = request.data['checkout']
            co_data['basket'] = "http://127.0.0.1:8000/oscar-api/baskets/"+str(basket.pk)+"/"
            c_ser = self.checkout_serializer(
                data=co_data, context={'request': request})
            if c_ser.is_valid():
                order = c_ser.save()
                basket.freeze()
                o_ser = self.order_serializer_class(
                    order, context={'request': request})
                oscarapi_post_checkout.send(
                    sender=self, order=order, user=request.user,
                    request=request, response=response)
                return response.Response(o_ser.data)

            return response.Response(c_ser.errors, status.HTTP_406_NOT_ACCEPTABLE)

The json request payload:

{
  "addproduct": {
    "url": "http://127.0.0.1:8000/oscar-api/products/1553/",
    "quantity": 1
  },
  "checkout": {
    "guest_email": "[email protected]",
    "total": "60.00",
    "shipping_method_code": "no-shipping-required",
    "first_name": "M",
    "last_name": "T",
    "phone_number": "12343455",
    "shipping_charge": {
      "currency": "USD",
      "incl_tax": "0.00",
      "excl_tax": "0.00",
      "tax": "0.0"
    },
    "shipping_address": {
      "country": "http://127.0.0.1:8000/oscar-api/countries/US/",
      "line1": "123 B St",
      "line2": "A",
      "line3": "B",
      "line4": "C",
      "notes": "Hello",
      "postcode": "94704",
      "state": "TX",
      "title": "Mr"
    }
  }
}

And response:

HTTP 200 OK
Allow: POST, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "number": "100035",
    "basket": "http://127.0.0.1:8000/oscar-api/baskets/35/",
    "url": "http://127.0.0.1:8000/oscar-api/orders/1/",
    "lines": "http://127.0.0.1:8000/oscar-api/orders/1/lines/",
    "owner": null,
    "billing_address": null,
    "currency": "USD",
    "total_incl_tax": "60.00",
    "total_excl_tax": "60.00",
    "shipping_incl_tax": "0.00",
    "shipping_excl_tax": "0.00",
    "shipping_address": {
        "id": 1,
        "country": "http://127.0.0.1:8000/oscar-api/countries/US/",
        "title": "Mr",
        "first_name": "",
        "last_name": "",
        "line1": "123 B St",
        "line2": "A",
        "line3": "B",
        "line4": "C",
        "state": "TX",
        "postcode": "94704",
        "search_text": "123 B St A B C TX 94704 United States of America",
        "phone_number": null,
        "notes": "Hello"
    },
    "shipping_method": "Free shipping",
    "shipping_code": "free-shipping",
    "status": "new",
    "guest_email": "[email protected]",
    "date_placed": "2017-03-23T07:01:03.672889Z",
    "payment_url": "You need to implement a view named 'api-payment' which redirects to the payment provider and sets up the callbacks.",
    "offer_discounts": [],
    "voucher_discounts": []
}

Doc improvement proposal - what happens after place an order.

Hello - When implementing the Place an order api I noticed a confirmation email is never sent. I presume this is because I am expected to create the payment logic myself and only send the email once payment is confirmed.

For reference Oscar sends the email in a view after running place_order. See here. The order api calls place_order but not the handle_successful_order method that involves sending the order.

My proposal is just to note this in the "place an order" section of the docs that it is expected the developer will call send_confirmation_message themselves once the order is final if they want the email sent. Unless there is a better way. I'm happy to send a pull request doc change if this my understanding is correct.

Why not using oscar.loading?

Going through the api's you might need to change a class or more, using the "loading.py" from oscar will allow more functionalities and easier access and modifications.

Checkout validation

I'm not sure if i'm doing it right. It seems that checkout validation in the CheckoutSerializer doesn't add the shipping charge to the total amount and if i do it myself via the OrderPlacementMixin validation fails because the total amount is validated against basket.total_incl_tax which does not include shipping. If i ignore this i end up with an order with a wrong total like this
#10 €48.00 €48.00

Discount €0.00 €0.00
Basket total €38.00 €38.00
Shipping total €10.00 €10.00
Order total €48.00 €48.00

A fix could be to use the OrderTotalCalculator to calculate the total after validation before create is called

Send ajax request to API

var basketForm = $(element).parent('form');
            var origin = window.location.origin;
            var endpoint =  origin + '/api/basket/add-product/';
            var add_prod_url = origin+"/api/products/"+2111;
            var csrf = o.cart.getCsrfToken();

            var data ={
                "url": add_prod_url,
                "quantity": 1
            };
            // $.post(endpoint, data,function (res) {
            //     alert(res);
            // });
            $.ajax({
                    type: 'POST',
                    data: data,
                    dataType: "json",
                    url: endpoint,
                    beforeSend: function(xhr, settings) {
                        xhr.setRequestHeader("X-CSRFToken", csrf);
                    }
                });

I am sending this request, however, it is producing 406 Error,
How I can sync user session with API session ?

Partly using API in an oscar website

In a scenario where an already existing website tries to use some part of the API (eg. implement ajax cart), basket managment is broken.
oscarapi uses session to manage basket_id whereas oscar uses cookies.
If the basket addition is done using API and a redirect happens for checkout or any other functionalty, request.basket is empty.
I solved this problem by overwriting basket APIs to use request.basket instead of operations.get_basket.
But, then the clients not using cookies wont be able to use the api.
So, had to override oscar.apps.basket.middleware to use session to manage basket.id.

Question is "Is having such a hybrid approach a bad idea altogether? If not then shoudn't we have a common approach to managing basket?"

Error in tests

"settings.OSCAR_MAX_BASKET_QUANTITY_THRESHOLD = None" in testoffer.py and testbasket.py is an error.

Allow overriding the default serializers

We might want to make the Serializers overridable by the project using the app. By creating abstract serializers users can implement their own just like currently possible with the oscar models/classes.

This would mean that we would use e.g. get_class('ProductSerializer') in the views

Compatibility with Django REST Framework 3

I have an existing oscar project that has some non-oscar parts using Django REST Framework 3. If I start using django-oscar-api for the oscar parts, will this cause an issue knowing that django-oscar-api requires DRF version less than 3?

Oscar price API

Hi,

I am using django oscar api and extending its functionality. Fetching a product price has a separate API. If I am displaying 20 products on a page, I need to call 20 extra APIs to fetch price. Product prices, i think, should be part of response returned by ProductList API.
My product will have multiple stock records but price will be same for all variants. Looking for a solution where I can make price as a part of productList API. Thanks in advance

Q: Use Oscar via API only in React app

I would like to integrate django-oscar-api into an existing django-rest-framework <--> React project.

In the django-oscar-api documentation, I'm finding bits and pieces talking about "mixing an Oscar stand-alone website and the API".

Therefore my question: Is it at all possible to make use of Oscar API only?

Should the JSON returned by a GET to /products/{id}/ of a child product include the images of its parent?

As it is right now, the json returned from a request to /products/{id}/ of a child product doesn't include images set on the parent. However, the Oscar dashboard doesn't let you set images on child products.

To me the expected behavior is that if I am requesting a child product, and there are images set on the parent, that I would be returned those.

As it is written, how should a client get the images of a child product?

Or is that a feature request? :)

New Release

Are you willing to upload the new release to PyPi anytime soon?

i get this issue builtins.DeprecationWarning

i try to use django oscar, i install based on documentation, everything iis fine, but when i go to basket url
i get this issue:

DeprecationWarning: Setting BasketView.extraat the class level is now deprecated. SetBasketView.factory_kwargs instead.

Ajax PUT request to update line quantity

When trying to update the quantity of a line in my basket I am getting this AssertionError:

AssertionError: The .update() method does not support writable nested fields by default.
Write an explicit .update() method for serializer oscarapi.serializers.basket.BasketLineSerializer, or set read_only=True on nested serialiser fields.

Am I doing anything wrong here? I am basically executing the exact same code as explained in the Example Usage section of the docs.

Thank you!

Oscar Api Checkout

Hello , in terms of checkout process during the request, the current latest version of django-oscar api has a checkout method already implemented.But , i need to know how to use PayPal with django oscar api and Stripes as a payment gateway.I mean , when someone try to buy you most select a payment type as the demo site has show.

Can someone explain how can i do that ? from the Api side???

How do you deal with API version?

So, I am deploying a mobile application with the present version of django-oscar-api.
Tomorrow there might be an update in the structure. The old mobile application might crash or functionalities might not work.

How is django-oscar-api architected?
Are you thinking of make django-oscar-api-v2, v3 versions when there are big changes?

Customizing LineAttributeSerializer

Hi,

Thank you for this great project.

I have a question on customizing LineAttributeSerializer. When getting basket lines (basket-line-detail) I'd like to return option's code with attributes. Meta model for LineAttributeSerializer is LineAttribute (AbstractLineAttribute) which has a fk relationship to catalogue.Option. I tried few things but I'm not quite sure how to go about returning option.code from it.

Any help would be greatly appreciated.

Updating line item quantity doesn't recalculate discounts

This issue might be related to #78.

Essentially, I am just sending a PUT request to update the quantity of a line item as explained in the example usage. However, after updating the line item quantity, discounts are not recalculated and in the response price_excl_tax and price_excl_tax_excl_discounts are equal. I would expect that count based offers are applied after updating the quantity.

Only when I request the whole basket again, the line items are updated.

checkout help

POST(basket, shipping_address,
[total, shipping_method_code, shipping_charge, billing_address])

its not entirely clear how each parameter should be represented. can someone please give an example how this is used?

Tests fail with postgresql

The oscarapi tests pass with sqlite as a db backend, and fail when run with postgres:

$ virtualenv env
$ . env/bin/activate
(env)web@vagrant-ubuntu-trusty-64:~$ git clone [email protected]:django-oscar/django-oscar-api.git
(env)web@vagrant-ubuntu-trusty-64:~$ cd django-oscar-api/
(env)web@vagrant-ubuntu-trusty-64:~$ make test
...
Ran 43 tests in 10.923s

OK
  • Swap out DATABASES in sandbox/settings.py with a postgresql configuration: ''ENGINE': 'django.db.backends.postgresql_psycopg2',' along with a working set of settings
    • pip install psycopg2
  • and re-run:
(env)web@vagrant-ubuntu-trusty-64:~$ make test
 ...
Ran 43 tests in 11.163s

FAILED (errors=3, failures=14)

The full output is pretty long. Here is one of the errors:

======================================================================
ERROR: A regular or anonymous user should not be able to fetch someone elses basket.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/web/django-oscar-api/oscarapi/tests/testbasket.py", line 169, in test_basket_read_permissions
    self.assertEqual(str(b.owner), 'nobody')
  File "/home/web/env/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 572, in __get__
    rel_obj = qs.get()
  File "/home/web/env/local/lib/python2.7/site-packages/django/db/models/query.py", line 357, in get
    self.model._meta.object_name)
DoesNotExist: User matching query does not exist.

Potential bug in `oscarapi_post_checkout` signal being sent

In oscarapi/views/checkout.py, the "response" argument of the oscarapi_post_checkout signal being sent is the entire rest_framework.response. I don't think that was the intent of the code.

from rest_framework import response


class CheckoutView(views.APIView):
    ...

    def post(self, request, format=None):
        ...
        oscarapi_post_checkout.send(
            sender=self, order=order, user=request.user,
            request=request, response=response)
        return response.Response(o_ser.data)

Probably should be something like this:

from rest_framework import response


class CheckoutView(views.APIView):
    ...

    def post(self, request, format=None):
        ...
        response = response.Response(o_ser.data)
        oscarapi_post_checkout.send(
            sender=self, order=order, user=request.user,
            request=request, response=response)
        return response

logging in

how do i use the the api to login using something like curl?

No module names api

I was using oscar api but after a while,'magically' following problem arose

ImportError: No module named 'api'

but, 'oscarapi' is in Installed apps,
and urls are defined as :

from oscarapi.app import application as api
 url(r'^api/', include('api.urls')),   

Products by Category

hi im currently working on a mobile app and realized that i cant find any code to get products by specified category. How could i implement this?

Oscarapi structure

Like oscar's dashboard and core apps, could we have sub-apps for the api as well? For example we could have the oscarapi/basket app which will have it's own app.py, serializers.py and views.py. This should be easy enough to do.

This could also help address the issue of extensibility. There was an attempt to make oscar's get_classes function work with modules that aren't present in oscar's core. I'm not sure what happened to that but now would be a good time to raise the issue again because with the sub-apps structure and a dynamic get_classes method in oscar, we'll have a highly extensible api app.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.