Skip to content

Instantly share code, notes, and snippets.

@SingularityMatrix
Last active August 29, 2015 14:22
Show Gist options
  • Save SingularityMatrix/dee15c1bdbbdb2990f0e to your computer and use it in GitHub Desktop.
Save SingularityMatrix/dee15c1bdbbdb2990f0e to your computer and use it in GitHub Desktop.
Batch API requests using REST API in Ruby on Rails [stress free way]
# app/controllers/api/v1/stockins_controller.rb
module Api
module V1
class StockinsController < ActionController::Base
before_filter :restrict_access
respond_to :json
def index
respond_with Stockin.all
end
def create
# respond_with Stockin.create(stockin_params) => this is enough to process a single request
sins = []
stockin_params.each do |sp|
sins = Stockin.create(sp)
end
render json: sins, status: 201
end
private
def restrict_access
authenticate_or_request_with_http_token do |token, options|
ApiKey.exists?(access_token: token)
end
end
# Never trust parameters from the scary internet, only allow the white list through.
def stockin_params
params.require(:stockins).map do |p|
ActionController::Parameters.new(p.to_hash)
.permit(:carton_id, :location_id, :no_of_boxes, :verify, :to_location, :carton_barcode)
end
end
end
end
end
CURL request -
curl -X POST -H "Authorization: Token token="72aad4fd93450943c40d0548c5240139"" -H "Content-Type: application/json" -H "Cache-Control: no-cache" -H -d '{
"stockins":
[{
"carton_barcode": "pro1-sup1-b1",
"no_of_boxes": 1,
"to_location": "NA-NA-NA-NA"
},
{
"carton_barcode": "pro1-sup1-b1",
"no_of_boxes": 2,
"to_location": "NA-NA-NA-NA"
}]
}' http://yourwebsite/api/v1/stockins
HTTP request -
POST /api/v1/stockins HTTP/1.1
Host: yourwebsite
Authorization: Token token="72aad4fd93450943c40d0548c5240139"
Content-Type: application/json
Cache-Control: no-cache
{
"stockins":
[{
"carton_barcode": "pro1-sup1-b1",
"no_of_boxes": 1,
"to_location": "NA-NA-NA-NA"
},
{
"carton_barcode": "pro1-sup1-b1",
"no_of_boxes": 2,
"to_location": "NA-NA-NA-NA"
}]
}
Header Status -
Status → 201 Created
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment