Giter Club home page Giter Club logo

jsonapi-resources's People

Contributors

adamworrall avatar adomokos avatar akharris avatar antonversal avatar arnezsng avatar barelyknown avatar davidmikesimon avatar dgeb avatar exelord avatar ggordon avatar iamvery avatar jerelmiller avatar johantell avatar kevinzwhuang avatar lgebhardt avatar mmartinson avatar nagirrab avatar nathanpalmer avatar olleolleolle avatar petesta avatar pmukerji avatar reidab avatar scottgonzalez avatar senid231 avatar slaskis avatar solirvine avatar tobias-grasse avatar utilityboy avatar whatthewhat avatar yawboakye 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jsonapi-resources's Issues

Key Type

Add a default configuration option for "key type", which can be overridden at the resource level.

The "key type" will be used by the verify_key method to check the key format. We should by default handle Integer, GUID and String formatted keys.

Sorting seems broken in 0.1.1

I'm trying to hit the following url:

basechurch.dev/testapp/v1/announcements?sort=+position

where position is just a regular attribute in my resource. This results in:

{
  "errors": [{
    "title":"Invalid sort format",
    "detail":" position must start with a direction (+ or -)",
    "id":null,
    "href":null,
    "code":119,
    "path":null,
    "links":null,
    "status":"bad_request"
  }]
}

I'm fairly certain that it has to do with Request#check_sort_criteria trying to see if " position" is a sortable field (see: leading space): https://github.com/cerebris/jsonapi-resources/blob/master/lib/jsonapi/request.rb#L193.

Or am I simply using this wrong?

Alternate solution for raising `JSONAPI::Exceptions::InvalidFieldValue` in `replace_fields`?

I'm currently using a callback before save to handle authorization.

module V1
  class BaseResource < JSONAPI::Resource
    # ...
    set_callback :save, :before, :authorize
    # ...
  end
end

I verify that authorization has been performed on each action in the ApplicationController:

class ApplicationController < JSONAPI::ResourceController
  # ...
  after_action :verify_policy_authorized, except: [:index]
  def verify_policy_authorized
    raise PolicyAuthorizationNotPerformedError unless policy_authorized?
  end
  # ...
end

Unfortunately, if an invalid value is submitted for an enum attribute the before save callback never happens because a JSONAPI::Exceptions::InvalidFieldValue is raised in _replace_fields. This causes verify_policy_authorized to not be called which raises the PolicyAuthorizationNotPerformedError.

I could obviously hack in a fix, but I wondered if this was a sign that a more general approach would be better. For example, should we provide a hook into exceptions raised and rescued which would allow the user of jsonapi-resources to handle things like bypassing policy authorization?

Build caching into JSONAPI::ResourceSerializer

Much like the 0.8.x versions of ActiveModel::Serializer, I propose that JSONAPI::ResourceSerializer should support the cached directive to enable caching of responses via Rails.cache.

The cache keys themselves should be based upon @model.cache_key.

There will be some gotchas with caching that will need to be tested for, namely around serializing multiple resources into a single payload, and the caching of any resources sideloaded via the include param.

I'll see if I can't put something together and open a PR.

Integrate with kaminari or will_paginate

I find this project the best one to implement the json api under a rails project.

The only thing I really miss is some kind of pagination integration (I know that it's still not in the json api spec, sadly), anyway, it'd be very useful some kind of integration with kaminari or will_paginate, with the ability to pass the page and page size to return.

It'd be awesome to also support different page size for included resources and to have some kind of config for a max_size (to block requests for 100000 items)

I guess this will be a placeholder until json-api/json-api#236 gets resolved

Request.parse_sort_criteria may not handle literal + in sort params

I opened an equivalent issue on the JSON API spec project: json-api/json-api#486

If I am not mistaken, many web servers see the plus symbol ("+") as a substitute for a white space or "%20" when sent as a query param in the URL. For example, this request

GET /people?sort=+age,+name

shows up as " age, name" to the Request.parse_sort_criteria method. Which is a total bummer for the if statement

if sort.start_with?('+')
  sort_criteria[:direction] = :asc
elsif sort.start_with?('-')
  sort_criteria[:direction] = :desc
else
  @errors.concat(...)
end

The spec compliant GET request leads to a 400 error because " age" and " name" both start with a white space instead of a "+"!

I find I can address this by either allowing a leading white space to behave as a + (e.g. sort.start_with?(' ')) or using %2b to represent + in the query params and using something like sort_criteria = URI.unescape(sort_criteria) to decode %2b into +.

Is there a preference for using one, the other, or both?

Configure for use without ActiveRecord?

In experimenting with this gem, I seem to run into trouble trying to use this with a NoSQL-style database instead of ActiveRecord. When trying to create new records with POST, I encounter the error:

uninitialized constant JSONAPI::ActiveRecordOperationsProcessor::ActiveRecord

Can the gem be configured to use alternative data storage strategies?

Thanks.

Going to be full-featured?

I'm really excited with jsonapi, it fits my needs with elegance and simplicity. This implementation seems the best for my needs and looks promising.

I thought about several features so decided to ask more general question. Will it be a full-featured implementation with all the features the spec provides? Including optional enabling of optional features (no force usage) and so on... Because it looks like some other implementations chosen one of "possible ways" (forced a concrete set of optional features).

As a developer I wish to know if I can rely on this implementation. (Also would be glad to provide some PRs if so).

I was thinking about URL Templates ("links" object) primarily. But now I'm waiting for the result of json-api/json-api#311.

Support for non-CRUD actions

Hey, I had a use-case where I was trying to create a controller action which didn't fit neatly into CRUD actions. I'm wondering if there's a way to do this in jsonapi-resources without too much trouble. I'd like to take advantage of the standardized success/error response formatting, but don't want to play too much around with the internals to achieve this goal. Anyone have any ideas?

`has_many` with different public field

I'm having issues using the has_many association helper and want to know if I am doing some obviously incorrect before I explore putting together a PR.

Here is an example of the models. We use normal integer primary keys internally, but externally we only display the UUID.

class Domain < ActiveRecord::Base
  # id (pk) integer
  # guid
    has_many :dns_records, class_name: DNS::Record

end

class DNS::Record < ActiveRecord::Base
  # id (pk) integer
  # domain_id - integer
  # guid
  belongs_to :domain
end

This is what we are trying to do:

class DomainResource < JSONAPI::Resource
  # key :id
  attributes :id, :name, :tld
  attribute :created_at, format: :date_time
  attribute :updated_at, format: :date_time

  has_many :records, class_name: 'DNS::Record', key: 'dns_record_ids', primary_key: 'guid'

  def id
    @model.guid
  end

class RecordResource < JSONAPI::Resource
  attribute :id

  def id
    @model.guid
  end
end

However this is not working. Any tips? Is this a use-case that is unsupported and I should put together a PR?

Support for models with namespaces

Am I missing something or is it not possible to specify a model with a namespace for a given Resource?

For example, how would I create a resource for Test::User?

Filtering with .where method: no matches without ActiveRecord

I am really excited about the progress of JSON API spec and the JSON API Resources Gem.

In my experiments with the gem, I found the following to be incompatible with Mongoid, the ActiveRecord replacement for integrating with MongoDB.

def apply_filter(records, filter, value)
  records.where(filter => value)
end

The value passed to this method is always an array. In ActiveRecord, passing an array value to the where method builds an IN SQL query. The challenge with something like Mongoid is that values can be stored as arrays. Thus, Contact.where(:github => ['realityendshere']) seems to search for contact records where the github property is exactly equal to the array ['realityendshere'] and does not return the expected results.

It's easy to override this method in my app's resources:

def self.apply_filter(records, filter, value)
  records.in(filter => value)
end

Hopefully, this helps anyone else trying to understand how jsonapi-resources gem works with ActiveRecord alternatives.

Reworking Context in Resources

I have a need to access the context when overriding the attribute setters and getters on a resource. Adding a context parameter to these methods is cumbersome. I think a better approach is to rework the way resources interact with context.

I am proposing that a resource instance will posses a context which is set when the resource is created. Resource class methods will continue to require an optional context parameter.

This change will break some methods that override the default resource methods. But it will also simplify quite a lot of code. Making all resource instances exist relative to a context removes the need to pass context around across many layers. For example we could remove the context from the ResourceSerializer, where it only exists to pass it through to the resource methods. In addition the context will be available in any method you need to override, without the need to explicitly pass it in. The downside is all resource creations will require a context.

I would like to make this change for the next version.

Validating ownership of associated objects

I got the following models

class Account < ActiveRecord::Base
  has_many :issuers
  has_many :invoices, through: :issuers
end

class Invoice < ActiveRecord::Base
  belongs_to :issuer
end

class Issuer < ActiveRecord::Base
  has_many :invoices
end

I want to allow user to create/update an invoice with provided issuer ID, but I want it to be an issuer only from the scope of his account. I can't validate it on model level (unless I add redundant account association to the invoice). I'm wondering if you have a way to approach this issue?

In ordinary rails app where you create/update only a single record I would probably do something like this:

@invoice.issuer = current_account.issuers.find(params[:invoice][:issuer_id])

In an application using JSON API controllers I don't see a clean way to achieve the same when creating/updating multiple records at once is possible. What do you recommend?

Camelized keys in json

Very pleased to see JR surface. I'm planning on using jsonapi-resources with ember-orbit so I'm putting together an example app at the moment. I see that the json keys are currently underscored but shouldn't they be converted to camelized keys?

Unable to override apply_filter

I highly suspect this is a problem on my side but I just want to confirm as well as see if you have any insight on what could be wrong.

I'm trying to implement filtering for one of my resources like so:

+  filter :latest
+
+  def apply_filter(records, filter, value)
+    raise "ERROR"
+  end

https://github.com/openmcac/basechurch/pull/18/files

But my resource's #apply_filter never seems to be called. I've put breakpoints in Resource#find and have verified that, at the point that it's supposed to call apply_filter, self is my subclass... However, when it's fired, it is only calling Resource#apply_filter and my method is never called nor is "ERROR" ever raised.

In fact, it seems that I can't override anything from Resource.

Calling the method directly from my specs, does raise the runtime error though.

Are there any public examples of apply_filter working?

Has_one relation doesn't check for existence

I'm not sure if I'm doing something wrong but I have a has_one relationship in one of my resources and if I create an instance using the create route and put in a links parameter. It doesn't check if the associated record exists before retrieving it.

Improve documentation on filters

I have read the docs and done an above review of filters and still don't really understand their effect, or what do they offer that cannot be achieved through the usage of fetchable_fields and finders. I'd like somebody to shed more light on this.

Single resource rendered as array

A single resource seems to be rendered as an array in the resulting JSON, even though the JSON API documentation states that it should simply be a single part of the hash.

The repository's documentation states the following:

require 'jsonapi/resource_serializer'
post = Post.find(1)
JSONAPI::ResourceSerializer.new.serialize(PostResource.new(post))

which results in

{
  posts: [{
    id: 1,
    title: 'New post',
    body: 'A body!!!',
    links: {
      section: nil,
      author: 1,
      tags: [1,2,3],
      comments: [1,2]
    }
  }]
}

even though post = Post.find(1) indicates that we're dealing with only one resource.

The desired json would look like this:

{
  post: {
    id: 1,
    title: 'New post',
    body: 'A body!!!',
    links: {
      section: nil,
      author: 1,
      tags: [1,2,3],
      comments: [1,2]
    }
  }
}

Is there a way to return a single resource to comply with the JSON API? I perused the source code but couldn't find any method that would do that.

Authorization

Hey guys,

This gem/library looks great! What about directly supporting an option to easily hook up authorization instead of requiring the resource controller index/show/create/update/destroy methods to be overridden?

Something like a simple interface that filters for index/read_list, returns true/false for show/create/update/destroy, and if in the future updating lists or destroying lists are supported, the interface could be updated to support filtering those as well. Than it would be straight forward for whoever to override it to support their preferred method of authorization, such as pundit or cancancan. I wouldn't mind implementing this if you guys are interested.

Top level links

Support creation of the top level links hash.

I think this should be done in the setup of the request object and provided to the serializer in the initializer. Otherwise the serializer will require full knowledge of the request in order to create the proper links.

Links should include a full query string, including filter, sort, and `page parameters.

`undefined method 'id' for nil:NilClass` when include nullable association

undefined method 'id' for nil:NilClass on resource.rb line 24.

Occurs when include resources with association set to nil.

class ContactResource < JSONAPI::Resource
  has_one :manager # may be nil
end

GET /contacts?include=manager causes error only if whatever contact has manager = nil

Looks like some explicit check for model is needed on resource_serializer.rb line 174.

p.s.: full lib trace

jsonapi-resources (0.0.9) lib/jsonapi/resource.rb:24:in `id'
jsonapi-resources (0.0.9) lib/jsonapi/resource_serializer.rb:175:in `block in links_hash'
jsonapi-resources (0.0.9) lib/jsonapi/resource_serializer.rb:153:in `each'
jsonapi-resources (0.0.9) lib/jsonapi/resource_serializer.rb:153:in `each_with_object'
jsonapi-resources (0.0.9) lib/jsonapi/resource_serializer.rb:153:in `links_hash'
jsonapi-resources (0.0.9) lib/jsonapi/resource_serializer.rb:117:in `object_hash'
jsonapi-resources (0.0.9) lib/jsonapi/resource_serializer.rb:189:in `block (2 levels) in links_hash'
jsonapi-resources (0.0.9) lib/jsonapi/resource_serializer.rb:185:in `each'
jsonapi-resources (0.0.9) lib/jsonapi/resource_serializer.rb:185:in `block in links_hash'
jsonapi-resources (0.0.9) lib/jsonapi/resource_serializer.rb:153:in `each'
jsonapi-resources (0.0.9) lib/jsonapi/resource_serializer.rb:153:in `each_with_object'
jsonapi-resources (0.0.9) lib/jsonapi/resource_serializer.rb:153:in `links_hash'
jsonapi-resources (0.0.9) lib/jsonapi/resource_serializer.rb:117:in `object_hash'
jsonapi-resources (0.0.9) lib/jsonapi/resource_serializer.rb:100:in `block in process_primary'
jsonapi-resources (0.0.9) lib/jsonapi/resource_serializer.rb:94:in `each'
jsonapi-resources (0.0.9) lib/jsonapi/resource_serializer.rb:94:in `process_primary'
jsonapi-resources (0.0.9) lib/jsonapi/resource_serializer.rb:31:in `serialize_to_hash'
jsonapi-resources (0.0.9) lib/jsonapi/resource_controller.rb:19:in `index'

How should polymorphic relationships be handled?

I have a class with a polymorphic relationship.

class Identification < ActiveRecord::Base
  belongs_to :identified, polymorphic: true
end

I would like to do something like this:

class IdentificationResource < BaseResource
  has_one :identified, polymorphic: true
end

This doesn't appear to be supported by jsonapi-resources yet (I checked master and jsonapi_rc2), but since polymorphism is supported in RC2, it seems like we should add it.

What are you thinking for this feature? I'd be happy to help.

Update relationship has one should send payload with pluralised key

The current test seems to be out of line with the jsonapi spec,

def test_update_relationship_has_one
  ruby = Section.find_by(name: 'ruby')

  post :create_association, {post_id: 3, association: 'section',
                 section: ruby.id }

  assert_response :success
  assert_equal 1, json_response['posts'].size
  assert_equal 3, json_response['posts'][0]['links']['author']
  assert_equal  ruby.id, json_response['posts'][0]['links']['section']
  assert_equal 'AAAA', json_response['posts'][0]['body']
end

from the spec

A to-one relationship MAY be added by sending a POST request with an individual primary resource to the URL of the relationship. For example:

POST /articles/1/links/author
Content-Type: application/vnd.api+json
Accept: application/vnd.api+json

{
"people": "12"
}

notice that the key is pluralised in the example from the spec but it's singular in the test case.

Extracting the loading of source and related resources in controller actions

I'd like to ensure that a user is authorized to view a related resource before it is rendered, but there's no way currently without completely reimplementing the get_related_resource method.

Here's the current implementation of get_related_resource in JSONAPI::ResourceController:

def get_related_resource
  association_type = params[:association]
  source_resource = @request.source_klass.find_by_key(@request.source_id, context: context)

  serializer = JSONAPI::ResourceSerializer.new(@request.source_klass,
                                               include: @request.include,
                                               fields: @request.fields,
                                               base_url: base_url,
                                               key_formatter: key_formatter,
                                               route_formatter: route_formatter)

  render json: serializer.serialize_to_hash(source_resource.send(association_type))
end

Ideally, we would extract two methods that could be overridden without needing to completely reimplement this method. Something like:

def get_related_resource
  source_resource = load_source_resource(@request)
  related_resource = load_related_resource(source_resource, params[:association])
  serializer = JSONAPI::ResourceSerializer.new(@request.source_klass,
                                               include: @request.include,
                                               fields: @request.fields,
                                               base_url: base_url,
                                               key_formatter: key_formatter,
                                               route_formatter: route_formatter)

  render json: serializer.serialize_to_hash(related_resource)
end

def load_source_resource(request)
  # ...
end

def load_related_resource(source_resource, association_name)
  # ...
end

With these methods extracted, users of the library would have the option of authorizing the source and related resources before they're rendered. Something like:

def load_related_resource(source_resource, association_name)
  related_resource = source_resource.public_send(association_name)
  unless authorized?(context[:current_user], related_resource.model)
    raise NotAuthorizedError
  end
  related_resource
end

I could also imagine handling this requirement by adding a new callback (before_render maybe?). But I think that I prefer the method that I mentioned above.

For what it's worth, a similar problem exists with other controller actions too (some can be handled with the existing callbacks, some can't). We should use similar approaches for each action.

I'd be happy to write a PR for this tomorrow, but I wanted to discuss this issue and approach before adding the feature.

`primary_key` field does not appear to work

Changing the primary key on a has_many association does not appear to work as it always falls back to id regardless of the value.

class DomainResource < JSONAPI::Resource
  attributes :id, :name, :tld, :serial_number, :created_at, :updated_at

  has_many :dns_records, primary_key: 'guid'
end

Looking through the specs, we also cannot find a spec to verify the primary_key functionality. We do see a test for class_name though

resource_for assumes top level resource class

I have my resource classes nested, and I get the following error when trying to start my application if I use the jsonapi_resources route helper:

lib/jsonapi/resource_for.rb:14:in `rescue in resource_for': JSONAPI: Could not find resource 'api/v1/users'. (Class Api::V1::UserResource not found) (NameError)

This is because my Ruby version is greater than 2.0, the and the conditional behaviour of resource_for uses Object.const_get which doesn't allow nesting, so the call should be:

Object.const_get('Api').const_get('V1').const_get('UserResource')

If I comment out the 2.0 version and allow it to use Rails safe_constantize, it works without issue. I would submit a PR but personally I would just use safe_constantize in all versions, and I don't know the reasoning behind using Object.const_get, the only possible reason I can think of is so that resource_for has a pure Ruby implementation, but Rails is specified in the Gemfile and I'm pretty sure other parts of the project depend on it.

Booleans serialized to string

I have a custom attribute in my model that returns a boolean. These are always serialized into either "false" or "true" instead of true boolean values.

Am I missing something or is this a bug?

Support to-many relationships as collection objects

Currently, adding objects to a to-many relationship using the collection object passes incorrectly data (namely, the collection object) to the target model. Most target models then blow up, since they are expecting an array of IDs.

Example object with a linked collection object:

//...
  {
    "id": "1",
    "title": "Rails is Omakase",
    "links": {
      "comments": {
        "href": "http://example.com/comments/5,12,17,20",
        "ids": [ "5", "12", "17", "20" ],
        "type": "comments"
      }
    }
  }
//...

Expected result: JSONAPI::ResourceController correctly enforces the type constraint and then properly sanitizes and flattens the collection object.

Support Meta

JR should support meta members. JSON API now allows meta in the top level, in a resource, and in a link object. Details of both custom meta information and standard JR meta information (if any) still needs to be defined.

Updating toOne relationship incompatible with jsonapi-resources?

Hard to say which project this issue belongs in but this seems as good a place as any.

I'm putting together an example app integrating JR with ember-orbit. I'm trying to create a new record with a hasOne relationship set. It works on the ember side but the update to the server is a put and JR expects a post. I've tried just switching the verb to PUT but JR and things progress further but the update from orbit has a pluralised key and JR seems to expect a singular key. @dgeb perhaps you could provide some clarity on what the payload should look like (I think it's correct on the ember-orbit side, see spec at http://jsonapi.org/format/#crud-updating-to-one-relationships).

The example is pretty easy to setup, if you want to look at a concrete example that's probably the best place to look, https://github.com/opsb/jr-ember-orbit-todos. If you do have a look you'll see that adding users works fine but adding todos fails with the above error (click on a user to see their todos).

serialize_to_hash: undefined method `_type'

I've been trying to integrate with a fairly basic project but whenever I serialize an object I get the error

NoMethodError: undefined method `_type' for #<Class:0x007faa896d8b08>
    from /Users/john/.rbenv/versions/2.2.0/lib/ruby/gems/2.2.0/gems/activerecord-4.2.0/lib/active_record/dynamic_matchers.rb:26:in `method_missing'
    from /Users/john/.rbenv/versions/2.2.0/lib/ruby/gems/2.2.0/bundler/gems/jsonapi-resources-ba8d7b40d61f/lib/jsonapi/resource_serializer.rb:129:in `attribute_hash'

Serializing by doing:

serializer = JSONAPI::ResourceSerializer.new(CrawlResource)
serializer.serialize_to_hash(Crawl.first)

Tried on 0.2.0 and master. Does anything leap out?

Seializer generates incorrect links when using inside an engine

When using JR in an engine, the resource serializer generates invalid URI's as it assumes a resourceful path and infers from the module nesting, however, an engine itself is namespaced and this namespace is included in the generated URI, i.e. for an API engine:

Rails.application.routes.draw do
  mount Api::Engine, at: 'api'
end

Api::Engine.routes.draw do
  namespace :v1 do
    resources :users
  end
end
module Api
  module V1
    class UsersController < ApplicationController
    end
  end
end
module Api
  module V1
    class UserResource < JSONAPI::Resource
      model_name 'Api::User'

      attribute :email
    end
  end
end

Generates:

{
  "data": [
    {
      "id": null,
      "email": "[email protected]",
      "type": "users",
      "links": {
        "self": "http://localhost:3000/api/v1/users/"
      }
    }
  ]
}

Make hook available to authorize resource?

I'd like to authorize resources using an approach like the convention followed by pundit. Here's what a typical controller action would look like (from the pundit documentation).

def update
  @post = Post.find(params[:id])
  authorize @post
  if @post.update(post_params)
    redirect_to @post
  else
    render :edit
  end
end

First you get the resource, then authorize it (which raises an exception if it fails), and then proceed.

For the index action, pundit provides the concept of a "scope" which gets the set of resources that the user has access to.

def index
  @posts = policy_scope(Post)
end

Anyhow, I don't see a straight forward way to hook into the controller methods since so much happens in the process_request_operations method. I think that it would be great for it to yield the resources so that they could be authorized in the middle of that method's execution.

What do you think?

HTTP/1.1 415 Unsupported Media Type

This probably isn't an issue but I am trying to get your example apps to work by following your process and I keep getting this error when I copy the curl command to create a resource.

curl -i -H "Accept: application/json" -H 'Content-Type:application/json' -X POST -d '{"contacts": {"first_name":"John", "last_name":"Doe", "email":"[email protected]"}}' http://localhost:3000/contacts
HTTP/1.1 415 Unsupported Media Type
X-Frame-Options: SAMEORIGIN
X-Xss-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Content-Type: application/json; charset=utf-8
Cache-Control: no-cache
X-Request-Id: 9b829ade-c674-49d6-9213-139312154469
X-Runtime: 0.051207
Server: WEBrick/1.3.1 (Ruby/2.1.5/2014-11-13)
Date: Sat, 28 Feb 2015 21:32:03 GMT
Content-Length: 292
Connection: Keep-Alive

{"errors":[{"title":"Unsupported media type","detail":"All requests that create or update resources must use the 'application/vnd.api+json' Content-Type. This request specified 'application/json.'","id":null,"href":null,"code":415,"path":null,"links":null,"status":"unsupported_media_type"}]}%

And the server log shows:

Processing by ContactsController#create as JSON
Parameters: {"contacts"=>{"first_name"=>"John", "last_name"=>"Doe", "email"=>"[email protected]"}, "contact"=>{}}
Can't verify CSRF token authenticity
Filter chain halted as :ensure_correct_media_type rendered or redirected
Completed 415 Unsupported Media Type in 1ms (Views: 0.3ms | ActiveRecord: 2.0ms)

I am pretty sure that I am doing something wrong here but wanted to post here so that if others are having the same issue they can hopefully find an quick answer. If I clone the repo it works. I have tried multiple versions of rails with no luck too.

Thanks

:id must be in the updateable_fields for RC2?

I'm working on converting an application over to the jsonapi_rc2 branch. I just noticed that a resource must have :id in its updateable_fields or else it receives a Param not allowed error (because :id is not in the formatted_allowed_fields). But, if you leave :id out of the data, you receive an "A key is required" error.

What is the intended behavior? I'm working on this today and can implement any changes that are required.

JSON API RC3 tracking

Hey there! I just wanted to let you know that JSON API has hit RC3, and we'd like client libraries to start implementing it like it was 1.0, as a final check that we're good for 1.0. I wanted to make this issue to let you know!

json-api/json-api#484

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.