There’s a lot of data out there on the Internet. We can access the data that other providers make available by consuming their
API - or application protocol interface - is a way to serve and access data. Accessing data from other sources allows you to use their data to build on their services, provide additional functionality, and use their data in new and inventive ways. This is an external
APIs are just as common. This makes data more accessible to our own application and associated services, something that’s especially useful when using
API in Rails is often a straightforward process, especially when the model is simple, since Rails has tools to make the data available in different formats.
Data available through
API in Rails, all we have to do is take the data from a model and serialize it - or turn it into
JSON data. We can do that using the
Here, Rails takes the post and converts it to
JSON to be served. We can serve different formats using
respond_to. We can also limit the data we’re serving and include associations as well.
However, as things get more complicated, we might want to find a cleaner way. We can instead use ActiveModel Serializers. You include and install the gem, run
rails g serializer <model name>, and modify the attributes in the new serializer class file. Then, when we respond with
JSON data, it serializes the model implicitly.
So now you can just do:
AJAX requests without reloading, you can do that by accessing these serializer-enabled controller actions.
You can read more about Rails ActiveModel Serializers in the Rails Guides.