Skip to content
Fetching contributors…
Cannot retrieve contributors at this time
533 lines (375 sloc) 14.5 KB

REST API

This guide covers the inner working of Spree’s RESTful API. It assumes a basic understanding of the principles of REST. More specifically, the guide will provide information on the following:

  • The various resources available through the API
  • How to make a basic API call
  • Specific examples on how to access certain resources
  • Tools and other suggestions for working with the API

endprologue.

Overview

The REST API is designed to give developers a convenient way to access data contained within Spree. With a standard read/write interface to store data, it is now very simple to write third party applications (ex. iPhone) that can talk to Spree. It is also possible to build sophisticated middleware applications that can serve as a bridge between Spree and a warehouse or inventory system.

Available Resources

INFO: The API currently only supports a limited number of resources. The current list reflects the needs of paying clients who funded the development of the API. The list will be expanded soon to cover additional resources. Adding more resources is simply a matter of making the time for testing and investigating possible security implications.

Spree currently supports RESTful access to the following resources:

  • Products
  • Variants
  • Orders
  • Line Items

JSON Data

Developers communicate with the Spree API using the JSON data format. Requests for data are communicated in the standard manner using the HTTP protocol.

For example, the request GET /api/products/a-product.json will produce output similar to the following:

{
“product”: {
“id”: 1,
“name”: “A product”,
“price”: “19.99”,
“available_on”: “2011-03-23T21:11:50Z”,
“permalink”, “a-product”
}
}

Making an API Call

Authentication

You will need an authentication token to access the API. These keys can be generated on the user edit screen within the admin interface. To make a request to the API, pass a X-Spree-Token header along with the request:

curl —header “X-Spree-Token: YOUR_KEY_HERE” http://example.com/api/products.json

Alternatively, you may also pass through the token as a parameter in the request if a header just won’t suit your purposes (i.e. JavaScript console debugging).

curl http://example.com/api/products.json?token=YOUR_KEY_HERE

The token allows the request to assume the same level of permissions as the actual user to whom the token belongs.

Other Supported Formats

Currently the API supports only the JSON format.

INFO: Supporting the XML format should not be difficult since Rails supports it out of the box. Volunteers who are willing to provide a patch (and tests) for XML support are encouraged to do so.

API Reference

API Rules

1. All successful requests for the API will return a status of 200.
2. Successful create and update requests will result in a status of 201 and 200 respectively.
3. Both create and update requests will return Spree’s representation of the data upon success.
4. If a create or update request fails, a status code of 422 will be returned, with a hash containing an “error” key, and an “errors” key. The errors value will contain all ActiveRecord validation errors encounterd when saving this record.
5. Delete requests will return status of 200, and no content.
6. Requests that list collections, such as /api/products will return a limited result set back.
7. Requests that list collections can be paginated through by passing a page parameter that is a number greater than 0.
8. If a resource can not be found, the API will return a status of 404.
9. Unauthorized requests will be met with a 401 response.

Products

Products support the following operations:

  • Index
  • Show
  • New
  • Create
  • Update
  • Destroy

Product data is returned like this:

{
“product”: {
“id”: 1,
“name”: “A product”,
“price”: “19.99”,
“available_on”: “2011-03-23T21:11:50Z”,
“permalink”, “a-product”
“variants”: {

  1. Variant attributes
    “option_values”: {
  2. Option value attributes
    }
    }
    “images”: {
  3. image attributes"
    }
    “option_types”: {
  4. option type attributes
    “option_values”: {
  5. option value attributes
    }
    }
    “product_properties”: {
  6. product property attributes
    }
    }
    }
Listing products

Products are displayed 25 at a time through this endpoint. To retrieve these products make a request to this endpoint:

GET /api/products.json

This request will return the first 25 products that are active (have an available_on timestamp prior to now) if the user is not an admin, or the first 25 of all products if the user is an admin.

This request can be paginated, which is done simply by passing through a page parameter on the request:

GET /api/products.json?page=1

The page size is not currently customizable.

If you are authenticating as an admin, you may tell the API to display deleted products as well:

GET /api/products.json?show_deleted=1

Searching for a product

To search for a particular product, make a request like this:

GET /api/products/search.json?q[name_cont]=Spree

The searching API is provided through the Ransack gem which Spree depends on. The `name_cont` here is called a predicate, and you can learn more about them by reading about Predicates on the Ransack wiki

A single product

To view the details for a single product, make a request using that product’s permalink:

GET /api/products/a-product.json

This will return a single product’s details.

You may also query by the product’s id attribute:

GET /api/products/1.json

Note that the API will attempt a permalink lookup before an ID lookup.

For the attributes contained in this output, please see the top of this section.

If a product cannot be found, a 404 response will be returned.

Pre-creation of a product

To query the API to find out what attributes are required to create a product, make a request like this:

GET /api/products/new.json

This request will inform the client of the fields that are required, so that the API client can indicate it to the user. Along with this are also the accepted parameters that the API will use in the creation of a product.

Creating a new product

NOTE: This route is only accessible by admins.

To create a new product through the API, make this request with the necessary parameters:

POST /api/products/create.json

For instance, a request to create a new product called “Headphones” with a price of $100 would look like this:

POST /api/products/create.json?product[name]=Headphones&product[price]=100

If this request succeeds, the API will return status 201.

If it fails, a 422 status will be returned, along with error data that can be used to determine what needs correcting.

Updating a product

NOTE: This route is only accessible by admins.

To update a product’s details, make this request with the necessary parameters:

PUT /api/products/a-product.json

For instance, to update a product’s name, send it through like this:

PUT /api/products/a-product.json?product[name]=Headphones

If this request succeeds, the API will return status 200.

If it fails, a 422 status will be returned, along with error data that can be used to determine what needs correcting.

Deleting a product

NOTE: This route is only accessible by admins.

To delete a product, make this request:

DELETE /api/products/a-product.json

NOTE: This request, much like a typical product “deletion”, will not actually remove the record from the database. It simply sets the deleted_at field to the current time on the product, as well as all of that product’s descendants.

The response for this request will be empty, with a 200 status.

Variants

Variants support the following operations:

  • Index
  • Show
  • New
  • Create
  • Update
  • Destroy

Variant data is returned like this:

{
“variant”: {
“id”: 1,
“name”: “A variant”,
“count_on_hand”: 1,
“price”: 19.99,
“weight”: 0.0,
“height”: 0.0,
“width”: 0.0,
“depth”: 0.0,
“is_master”: true,
“cost_price”: 9.99,
“option_values”: {

  1. option value attributes
    }
    }
    }
Listing variants

To see all variants, make this request:

GET /api/variants.json

Listing variants of a product

To see all variants (including the master variant) for a product, make either of these two requests:

GET /api/products/1/variants

  1. or
    GET /api/variants?product_id=1
Pre-creation of a variant

To learn how to create a variant, make this request:

GET /api/variants/new

This request will inform the client of the fields that are required, so that the API client can indicate it to the user.

There are no required attributes for a variant.

Creating a variant

To create a new variant for a product, make one of these two requests with the correct parameters:

POST /api/products/1/variants

  1. or
    POST /api/variants?product_id=1

For instance, a request to create a new variant with a price of $100 would look like this:

POST /api/variants/create.json?variant[price]=100&product_id=1

Updating a variant

To update a variant’s information, make one of these two requests with the correct parameters:

PUT /api/products/1/variants/2

  1. or
    PUT /api/variants/2?product_id=1

For instance, a request to update an existing variant with a price of $100 would look like this:

PUT /api/variants/2?variant[price]=100?product=1

Deleting a variant

To delete a variant, make one of these two requests:

DELETE /api/products/1/variants/2

  1. or
    DELETE /api/variants/2?product_id=1

Upon completion of this request the API will return a 200 status code.

Orders

Orders support the following operations:

  • Index
  • Show
  • New
  • Create
  • Adding address information
  • Adding shipping information

Order data is returned like this:

{
“order”: {
“id”: 1,
“number”: “R1234567”,
“item_total”: 100.0,
“total”: 100.0,
“adjustment_total”: 0.0,
“credit_total”: 0.0,
“payment_total”: 0.0,
“user_id”: 1,
“created_at”: ,
“updated_at”: ,
“completed_at”: ,
“state”: <one of: ‘cart’, ‘address’, ‘delivery’, ‘payment’, ‘confirm’ or ’complete’>,
“shipment_state”: <one of: ‘shipped’, ‘ready’, ‘pending’, ‘partial’ or ’backorder’>,
“payment_state”: <one of: ‘balance_due’, ‘failed’, ‘credit_owed’ or ’paid’>,
“email”: user@spreecommerce.com,
“special_instructions”: “Ring the bell”
“option_values”: {

  1. option value attributes
    }
    }
    }

In addition to this, the JSON response will also contain the following additional information if the order is in the “delivery” state:

{
“order”: {

“shipping_methods”: {
“shipping_method”: {
“id”: 1,
“name”: “UPS Ground”,
“cost”, 10.00
}
}
}
}

Viewing all orders

NOTE: This resource is only accessible by admins.

To view all orders for a request, make this request:

GET /api/orders

This will return 25 orders at a time. You can page through the orders by passing through the page parameter:

GET /api/orders?page=2

If you wish to limit the number of orders returned you may pass through the per_page attribute:

GET /api/orders?per_page=100

Viewing an order

To view an order, make this request:

GET /api/orders/R1234567

NOTE: Only admins or users that the order belongs to can make this request.

Creating an order

To create an order, make this request with the correct parameters:

POST /api/orders

For instance, to create an order containing a line item for a single variant who’s ID is “1” and quantity is 5, make this request:

POST /api/orders?order[line_items][][variant_id]=1&order[line_items[][quantity]=5

If you want to create an order with more than one variant, then continue to chain variant_id and quantity pairs, like this:

POST /api/orders?order[line_items][][variant_id]=1&order[line_items[][quantity]=5&order[line_items][][variant_id]=2&order[line_items[][quantity]=10

Adding address information to an order

To add address information to an order, make this request with the correct parameters:

PUT /api/orders/:number/address

This endpoint requires you to pass through both shipping address and billing address information at the same time. With an order number of R1234567, it would be done like this:

PUT /api/orders/R1234567/address?shipping_address[firstname]…

The address parameters are:

  • firstname
  • lastname
  • company
  • address1
  • address2
  • city
  • zipcode
  • phone
  • alternative_phone
  • country_id
  • state_id

Once valid address information has been submitted, the shipping methods available for this order will be returned inside a “shipping_methods” key inside the order:

{
“order”: {

“shipping_methods”: {
“shipping_method”: {
“id”: 1,
“name”: “UPS Ground”,
“cost”, 10.00
}
}
}
}

The order will also transition to being in the “delivery” state.

NOTE: If you submit a shipping address to this action that does not have a corresponding shipping method associated with it, the response will return a status of 422 and a message of “No shipping methods available for selected location, please change your address and try again.”

Selecting a delivery method for an order

To choose a delivery method for the order, pass along one ID from the “shipping_methods” response that you would receive from making a request to update the order’s address, or by making another request to /api/orders/R1234567 while the order is in the “delivery” state.

Make a request like this:

PUT /api/orders/R1234567?shipping_method_id=1

Upon a successful request, the order will transition to being in the “payment” state.

Emptying an order cart

To empty an order’s cart, make this request:

PUT /api/orders/:number/empty

All line items will be removed from the cart and the order’s information will be updated. Inventory that was previously depleted by this order will be repleted.

Jump to Line
Something went wrong with that request. Please try again.