SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Downloaden Sie, um offline zu lesen
How to
Implement
Active Model
Serializers
with Your
Rails API?
www.bacancytechnology.com
In this tutorial, we will learn how to make
serializers for Rails APIs and implement
them efficiently so that they can be
accommodated to versioning APIs too.
Table of Content
1. What is Active Model Serializers?
2. Importance and Usage of Active Model
Serializers
3. How to Implement Active Model
Serializers with Rails API?
4. Alternative of Active Model Serializers
5. Conclusion
What is
Active Model
Serializers?
Serializers: It describes which
attributes & relationships to be
serialized.
Adapters: It describes the way of
serializing those attributes &
relationships, i.e., how to serialize.
Serializer gem allows us to format our
JSON easily. It will enable us to select
only the data we want and access our
relationships with a single request.
Active Model Serializers provides a way
of creating custom JSON in an object-
oriented manner.
Active Model Serializer consists of two
components:
The serializer creates the relationship in
the backend and then translates it to the
frontend.
Importance
and Usage of
Active Model
Serializers
Active Model Serializers offers a way to
create custom JSON by representing
each resource as a class inherited from
Active Model Serializers. With the help
of a serializer, we need to make a single
request to the backend. With proper
association done through serialization,
the backend will fetch all the required
data needed by request rather than
requesting multiple times to multiple
models.
The primary usage of Active Model
Serializers is to create custom JSON
responses. By default, Rails provides a
way to render JSON, but we need a
serializer if we want to customize it.
How to
Implement
Active Model
Serializers
with Rails
API?
Here is the step-by-step guide to
implementing Active Model Serializers
with Rails API whose source code is
available in the Github repository.
In this demo, we will be installing two
dependencies-
⊿active_model_serializers gem
○To achieve the intention of
serialization
⊿faker gem
○To mock (fill) data
Let’s get started with building our demo
project for Active Model Serializer.
active_model_serializers
rack-cors
faker (development & test
environment only)
Create a new project by executing the
below-mentioned command
rails new active-model-serializer --api
Add below gems in your Gemfile
Install these newly added gems using
this command
$ bundle install
1. Create new project
2. Adding Gem
Firstly, we will create two models and
connect them to One-to-Many
relationships.
We’ve built an Employee model having
attributes (name, email, date_of_birth,
mobile_no, designation, salary). Which
belongs_to Manager model having the
attribute (name).
$ rails g model Manager name
$ rails g model Employee name email
dob:date mobile
designation salary:number
manager:references
3. Data Modeling
The Manager has_many employees. At
the same time, Employee belongs_to
only one manager.
After the model changes, migration is
necessary. Run the below command
$ rails db:migrate
We will now add routes for APIs-only
methods. The routes can extend with
other versioning.
4. Perform Migration
5. Configuration of
Routes
# config/routes.rb
Rails.application.routes.draw do
concern :api_base do
resources :employees
resources :managers
end
namespace :v1 do
concerns :api_base
end
end
Declare data seed file to insert mock
data for defined models. We can also
enter data manually into the database,
but it is easy with the seed file by
running a single command.
$ rails db:seed
Here’s the seeds.rb
# db/seeds.rb
6. Pre-defined Data
Added
Employee.destroy_all
Manager.destroy_all
managers = (1..20).map do
Manager.create!(
name: "manager"
)
end
employee = (1..50).map do
Employee.create!(
name: "employee",
email: "emp@gmail.com",
dob: "17-01-1988",
mobile: "8879544321",
designation: "Senior Developer",
salary: 35_000,
manager: managers.sample
)
end
We will define a serializer for each
model indicating what data to be
broadcasted over the network by
serializing the model. The attribute we
declared to be serialized can be further
defined to explain what data to be
passed for.
You can see the below example for the
model serializer.
7. Define Model
Serializer
#app/serializers/v1/employee_serialize
r.rb
module V1
class EmployeeSerializer <
ActiveModel::Serializer
attributes :id, :name, :email,
:designation, :manager
def manager
{
id: object.manager.id,
name: object.manager.name
}
end
end
end
#app/serializers/v1/manager_serializer.
rb
module V1
class ManagerSerializer <
ActiveModel::Serializer
attributes :id, :name, :employees
def employees
object.employees.map do
|employee|
{
id: employee.id,
name: employee.name,
email: employee.email,
designation: employee.designation
}
end
end
end
end
It’s time to define the controller for
respective models to serve serialized
objects over API by explicitly defining
serializers for individual models. Here,
we will define which serializer will be
used for passing data by JSON.
You can see the below example for
controllers.
8. Define Controller
#app/controllers/v1/employees_controlle
r.rb
module V1
class EmployeesController <
ApplicationController
def index
employees =
Employee.all.includes(:manager)
// used includes method to prevent N-
Query problem
render json: {
data:
ActiveModelSerializers::SerializableResou
rce.new(employees, each_serializer:
EmployeeSerializer),
message: ['Employee list fetched
successfully'],
status: 200,
type: 'Success'
}
end
def show
employee =
Employee.find(params[:id])
render json: {
data:
ActiveModelSerializers::SerializableReso
urce.new(employee, serializer:
EmployeeSerializer),
message: ['Employee profile fetched
successfully'],
status: 200,
type: 'Success'
}
end
end
end
#app/controllers/v1/managers_controlle
r.rb
module V1
class ManagersController <
ApplicationController
def index
managers =
Manager.all.includes(:employees)
render json: {
data:
ActiveModelSerializers::SerializableReso
urce.new(managers, each_serializer:
ManagerSerializer),
message: ['Manager list fetched
successfully'],
status: 200,
type: 'Success'
}
end
def show
manager = Manager.find(params[:id])
render json: {
data:
ActiveModelSerializers::SerializableReso
urce.new(manager, serializer:
ManagerSerializer),
message: ['Manager profile fetched
successfully'],
status: 200,
type: 'Success'
}
end
end
end
The output for the request to fetch
details of employees and managers APIs
is as shown below.
// GET
http://localhost:3000/v1/employees/1
9. End-point Response
{
"data":{
"id":1,
"name":"employee",
"email":"emp@gmail.com",
"designation":"Senior Developer",
"manager":{
"id":6,
"name":"manager"
}
},
"message":[
"Employee profile fetched
successfully"
],
"status":200,
"type":"Success"
}
// GET
http://localhost:3000/v1/managers/6
{
"data":{
"id":6,
"name":"manager",
"employees":[
{
"id":1,
"name":"employee",
"email":"emp@gmail.com",
"designation":"Senior Developer"
},
{
"id":33,
"name":"employee",
"email":"emp@gmail.com",
"designation":"Senior Developer"
},
{
"id":39,
"name":"employee",
"email":"emp@gmail.com",
"designation":"Senior Developer"
}
]
},
"message":[
"Manager profile fetched
successfully"
],
"status":200,
"type":"Success"
}
We can extend the API and serializers by
versioning them.
For creating another version of the
controller, create it under the path
app/controllers/v2/employees_controlle
r.rb
And for creating the serializer, create it
under the path
app/serializers/v2/employee_serializer.r
b.
Remember that the class you’re creating
for versioned API should fall under
module V2 (or whatever version you’re
defining for).
10. Versioning
Controller & Serializer
Created new project using rails new
active-model-serializer --api
Added required gems
Defined models
Migrated the schema
Configured routes for the API
Defined serializer for the respective
model
Implemented business logic in the
controller
Fetched data from API endpoints
Quick Summary
Here is the list of steps we performed to
build serializer APIs:
Alternative
of Active
Model
Serializers
JSONAPI-RB- It is considered a
highly performant and modular
JSON:API. There's a vibrant
community around it that has
produced this Ruby library
consisting of four micro-libraries and
two frameworks.
Fast JSON API- It is a lightning-fast
JSON:API serializer for Ruby Objects.
It is believed to be 25 times faster
than Active Model Serializers.
Blueprinter- It is a high-speed,
declarative, and API agnostic
serializer that uses composable
views for reducing duplication.
Conclusion
So, I hope you have a clear
understanding of What is Active Model
Serializers? Implementation, Usage, and
Alternatives of Active Model Serializers
in Rails 6. If you are looking for a helping
hand in your Ruby on Rails project, then
you’ve landed on the right page. Get in
touch with us to hire ROR developer
with the desired skillset at your ease and
convenience.
Thank You
www.bacancytechnology.com

Weitere Àhnliche Inhalte

Was ist angesagt?

[2014ë„ëŠŹì„žëŻžë‚˜] 시맚틱한 HTML5 ë§ˆíŹì—… ê”ŹìĄ° ì„€êł„, ì–Žë–»êȌ 할êčŒ?
[2014ë„ëŠŹì„žëŻžë‚˜] 시맚틱한 HTML5 ë§ˆíŹì—… ê”ŹìĄ° ì„€êł„, ì–Žë–»êȌ 할êčŒ?[2014ë„ëŠŹì„žëŻžë‚˜] 시맚틱한 HTML5 ë§ˆíŹì—… ê”ŹìĄ° ì„€êł„, ì–Žë–»êȌ 할êčŒ?
[2014ë„ëŠŹì„žëŻžë‚˜] 시맚틱한 HTML5 ë§ˆíŹì—… ê”ŹìĄ° ì„€êł„, ì–Žë–»êȌ 할êčŒ?
Nts Nuli
 
Chokudai search
Chokudai searchChokudai search
Chokudai search
AtCoder Inc.
 

Was ist angesagt? (20)

AtCoder Regular Contest 002
AtCoder Regular Contest 002AtCoder Regular Contest 002
AtCoder Regular Contest 002
 
AtCoder Regular Contest 029 è§ŁèȘŹ
AtCoder Regular Contest 029 è§ŁèȘŹAtCoder Regular Contest 029 è§ŁèȘŹ
AtCoder Regular Contest 029 è§ŁèȘŹ
 
Colors In CSS3
Colors In CSS3Colors In CSS3
Colors In CSS3
 
AtCoder Regular Contest 043 è§ŁèȘŹ
AtCoder Regular Contest 043 è§ŁèȘŹAtCoder Regular Contest 043 è§ŁèȘŹ
AtCoder Regular Contest 043 è§ŁèȘŹ
 
ViveăŻă˜ă‚ăŸă—ăŸ
ViveăŻă˜ă‚ăŸă—ăŸViveăŻă˜ă‚ăŸă—ăŸ
ViveăŻă˜ă‚ăŸă—ăŸ
 
Efficient, maintainable CSS
Efficient, maintainable CSSEfficient, maintainable CSS
Efficient, maintainable CSS
 
판별 ëȘšëžì„ 톔한 대ìČŽì–Ž 추출
판별 ëȘšëžì„ 톔한 대ìČŽì–Ž ì¶”ì¶œíŒëł„ ëȘšëžì„ 톔한 대ìČŽì–Ž 추출
판별 ëȘšëžì„ 톔한 대ìČŽì–Ž 추출
 
AtCoder Beginner Contest 002 è§ŁèȘŹ
AtCoder Beginner Contest 002 è§ŁèȘŹAtCoder Beginner Contest 002 è§ŁèȘŹ
AtCoder Beginner Contest 002 è§ŁèȘŹ
 
[2014ë„ëŠŹì„žëŻžë‚˜] 시맚틱한 HTML5 ë§ˆíŹì—… ê”ŹìĄ° ì„€êł„, ì–Žë–»êȌ 할êčŒ?
[2014ë„ëŠŹì„žëŻžë‚˜] 시맚틱한 HTML5 ë§ˆíŹì—… ê”ŹìĄ° ì„€êł„, ì–Žë–»êȌ 할êčŒ?[2014ë„ëŠŹì„žëŻžë‚˜] 시맚틱한 HTML5 ë§ˆíŹì—… ê”ŹìĄ° ì„€êł„, ì–Žë–»êȌ 할êčŒ?
[2014ë„ëŠŹì„žëŻžë‚˜] 시맚틱한 HTML5 ë§ˆíŹì—… ê”ŹìĄ° ì„€êł„, ì–Žë–»êȌ 할êčŒ?
 
CSS Systems
CSS SystemsCSS Systems
CSS Systems
 
æ•°ć­Šăƒ—ăƒ­ă‚°ăƒ©ăƒ ă‚’ Haskell ă§æ›žăăčき 6 た理由
æ•°ć­Šăƒ—ăƒ­ă‚°ăƒ©ăƒ ă‚’ Haskell ă§æ›žăăčき 6 ăźç†ç”±æ•°ć­Šăƒ—ăƒ­ă‚°ăƒ©ăƒ ă‚’ Haskell ă§æ›žăăčき 6 た理由
æ•°ć­Šăƒ—ăƒ­ă‚°ăƒ©ăƒ ă‚’ Haskell ă§æ›žăăčき 6 た理由
 
Abc009
Abc009Abc009
Abc009
 
#5 CRUD no MongoDB
#5   CRUD  no MongoDB#5   CRUD  no MongoDB
#5 CRUD no MongoDB
 
Use of Lists and Tables in HTML
Use of Lists and Tables in HTMLUse of Lists and Tables in HTML
Use of Lists and Tables in HTML
 
AtCoder Beginner Contest 010 è§ŁèȘŹ
AtCoder Beginner Contest 010 è§ŁèȘŹAtCoder Beginner Contest 010 è§ŁèȘŹ
AtCoder Beginner Contest 010 è§ŁèȘŹ
 
ćčłæș–ćŒ–ăźă™ă™ă‚æ–čäș‹äŸ‹ă§ć­Šă¶ćčłæș–ćŒ–ïœž
ćčłæș–ćŒ–ăźă™ă™ă‚æ–čäș‹äŸ‹ă§ć­Šă¶ćčłæș–ćŒ–ïœžćčłæș–ćŒ–ăźă™ă™ă‚æ–čäș‹äŸ‹ă§ć­Šă¶ćčłæș–ćŒ–ïœž
ćčłæș–ćŒ–ăźă™ă™ă‚æ–čäș‹äŸ‹ă§ć­Šă¶ćčłæș–ćŒ–ïœž
 
ă‚ąăƒ©ăƒ“ă‚ąèȘžăšăƒšăƒ«ă‚·ăƒŁèȘžăźèŠ‹ćˆ†ă‘æ–č #DSIRNLP 5
ă‚ąăƒ©ăƒ“ă‚ąèȘžăšăƒšăƒ«ă‚·ăƒŁèȘžăźèŠ‹ćˆ†ă‘æ–č #DSIRNLP 5ă‚ąăƒ©ăƒ“ă‚ąèȘžăšăƒšăƒ«ă‚·ăƒŁèȘžăźèŠ‹ćˆ†ă‘æ–č #DSIRNLP 5
ă‚ąăƒ©ăƒ“ă‚ąèȘžăšăƒšăƒ«ă‚·ăƒŁèȘžăźèŠ‹ćˆ†ă‘æ–č #DSIRNLP 5
 
Testing and Deployment - Full Stack Deep Learning
Testing and Deployment - Full Stack Deep LearningTesting and Deployment - Full Stack Deep Learning
Testing and Deployment - Full Stack Deep Learning
 
ăƒ€ăƒ–ăƒ«é…ćˆ—ăźè±†çŸ„è­˜
ăƒ€ăƒ–ăƒ«é…ćˆ—ăźè±†çŸ„è­˜ăƒ€ăƒ–ăƒ«é…ćˆ—ăźè±†çŸ„è­˜
ăƒ€ăƒ–ăƒ«é…ćˆ—ăźè±†çŸ„è­˜
 
Chokudai search
Chokudai searchChokudai search
Chokudai search
 

Ähnlich wie How to Implement Active Model Serializers with Your Rails API?

WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Fabio Franzini
 

Ähnlich wie How to Implement Active Model Serializers with Your Rails API? (20)

Create a new project in ROR
Create a new project in RORCreate a new project in ROR
Create a new project in ROR
 
Rails 5 – most effective features for apps upgradation
Rails 5 – most effective features for apps upgradationRails 5 – most effective features for apps upgradation
Rails 5 – most effective features for apps upgradation
 
Method and decorator
Method and decoratorMethod and decorator
Method and decorator
 
RoR 101: Session 2
RoR 101: Session 2RoR 101: Session 2
RoR 101: Session 2
 
Workshop 16: EmberJS Parte I
Workshop 16: EmberJS Parte IWorkshop 16: EmberJS Parte I
Workshop 16: EmberJS Parte I
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web Apps
 
Migration from Rails2 to Rails3
Migration from Rails2 to Rails3Migration from Rails2 to Rails3
Migration from Rails2 to Rails3
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
Supa fast Ruby + Rails
Supa fast Ruby + RailsSupa fast Ruby + Rails
Supa fast Ruby + Rails
 
Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end Framework
 
Heroku pop-behind-the-sense
Heroku pop-behind-the-senseHeroku pop-behind-the-sense
Heroku pop-behind-the-sense
 
MongoDB Days UK: Building Apps with the MEAN Stack
MongoDB Days UK: Building Apps with the MEAN StackMongoDB Days UK: Building Apps with the MEAN Stack
MongoDB Days UK: Building Apps with the MEAN Stack
 
Rail3 intro 29th_sep_surendran
Rail3 intro 29th_sep_surendranRail3 intro 29th_sep_surendran
Rail3 intro 29th_sep_surendran
 
One does not simply "Upgrade to Rails 3"
One does not simply "Upgrade to Rails 3"One does not simply "Upgrade to Rails 3"
One does not simply "Upgrade to Rails 3"
 
Go swagger tutorial how to create golang api documentation using go swagger (1)
Go swagger tutorial how to create golang api documentation using go swagger (1)Go swagger tutorial how to create golang api documentation using go swagger (1)
Go swagger tutorial how to create golang api documentation using go swagger (1)
 
Ams adapters
Ams adaptersAms adapters
Ams adapters
 
Scalable web application architecture
Scalable web application architectureScalable web application architecture
Scalable web application architecture
 
Javascript Frameworks for Well Architected, Immersive Web Apps
Javascript Frameworks for Well Architected, Immersive Web AppsJavascript Frameworks for Well Architected, Immersive Web Apps
Javascript Frameworks for Well Architected, Immersive Web Apps
 
Ember Data and JSON API
Ember Data and JSON APIEmber Data and JSON API
Ember Data and JSON API
 
PHP FUNCTIONS
PHP FUNCTIONSPHP FUNCTIONS
PHP FUNCTIONS
 

Mehr von Katy Slemon

Mehr von Katy Slemon (20)

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
 

KĂŒrzlich hochgeladen

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

KĂŒrzlich hochgeladen (20)

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 

How to Implement Active Model Serializers with Your Rails API?

  • 1. How to Implement Active Model Serializers with Your Rails API? www.bacancytechnology.com
  • 2. In this tutorial, we will learn how to make serializers for Rails APIs and implement them efficiently so that they can be accommodated to versioning APIs too.
  • 3. Table of Content 1. What is Active Model Serializers? 2. Importance and Usage of Active Model Serializers 3. How to Implement Active Model Serializers with Rails API? 4. Alternative of Active Model Serializers 5. Conclusion
  • 5. Serializers: It describes which attributes & relationships to be serialized. Adapters: It describes the way of serializing those attributes & relationships, i.e., how to serialize. Serializer gem allows us to format our JSON easily. It will enable us to select only the data we want and access our relationships with a single request. Active Model Serializers provides a way of creating custom JSON in an object- oriented manner. Active Model Serializer consists of two components: The serializer creates the relationship in the backend and then translates it to the frontend.
  • 6. Importance and Usage of Active Model Serializers
  • 7. Active Model Serializers offers a way to create custom JSON by representing each resource as a class inherited from Active Model Serializers. With the help of a serializer, we need to make a single request to the backend. With proper association done through serialization, the backend will fetch all the required data needed by request rather than requesting multiple times to multiple models. The primary usage of Active Model Serializers is to create custom JSON responses. By default, Rails provides a way to render JSON, but we need a serializer if we want to customize it.
  • 9. Here is the step-by-step guide to implementing Active Model Serializers with Rails API whose source code is available in the Github repository. In this demo, we will be installing two dependencies- ⊿active_model_serializers gem ○To achieve the intention of serialization ⊿faker gem ○To mock (fill) data Let’s get started with building our demo project for Active Model Serializer.
  • 10. active_model_serializers rack-cors faker (development & test environment only) Create a new project by executing the below-mentioned command rails new active-model-serializer --api Add below gems in your Gemfile Install these newly added gems using this command $ bundle install 1. Create new project 2. Adding Gem
  • 11. Firstly, we will create two models and connect them to One-to-Many relationships. We’ve built an Employee model having attributes (name, email, date_of_birth, mobile_no, designation, salary). Which belongs_to Manager model having the attribute (name). $ rails g model Manager name $ rails g model Employee name email dob:date mobile designation salary:number manager:references 3. Data Modeling
  • 12. The Manager has_many employees. At the same time, Employee belongs_to only one manager. After the model changes, migration is necessary. Run the below command $ rails db:migrate We will now add routes for APIs-only methods. The routes can extend with other versioning. 4. Perform Migration 5. Configuration of Routes
  • 13. # config/routes.rb Rails.application.routes.draw do concern :api_base do resources :employees resources :managers end namespace :v1 do concerns :api_base end end
  • 14. Declare data seed file to insert mock data for defined models. We can also enter data manually into the database, but it is easy with the seed file by running a single command. $ rails db:seed Here’s the seeds.rb # db/seeds.rb 6. Pre-defined Data Added
  • 15. Employee.destroy_all Manager.destroy_all managers = (1..20).map do Manager.create!( name: "manager" ) end employee = (1..50).map do Employee.create!( name: "employee", email: "emp@gmail.com", dob: "17-01-1988", mobile: "8879544321", designation: "Senior Developer", salary: 35_000, manager: managers.sample ) end
  • 16. We will define a serializer for each model indicating what data to be broadcasted over the network by serializing the model. The attribute we declared to be serialized can be further defined to explain what data to be passed for. You can see the below example for the model serializer. 7. Define Model Serializer
  • 17. #app/serializers/v1/employee_serialize r.rb module V1 class EmployeeSerializer < ActiveModel::Serializer attributes :id, :name, :email, :designation, :manager def manager { id: object.manager.id, name: object.manager.name } end end end
  • 18. #app/serializers/v1/manager_serializer. rb module V1 class ManagerSerializer < ActiveModel::Serializer attributes :id, :name, :employees def employees object.employees.map do |employee| { id: employee.id, name: employee.name, email: employee.email, designation: employee.designation } end end end end
  • 19. It’s time to define the controller for respective models to serve serialized objects over API by explicitly defining serializers for individual models. Here, we will define which serializer will be used for passing data by JSON. You can see the below example for controllers. 8. Define Controller
  • 20. #app/controllers/v1/employees_controlle r.rb module V1 class EmployeesController < ApplicationController def index employees = Employee.all.includes(:manager) // used includes method to prevent N- Query problem render json: { data: ActiveModelSerializers::SerializableResou rce.new(employees, each_serializer: EmployeeSerializer),
  • 21. message: ['Employee list fetched successfully'], status: 200, type: 'Success' } end def show employee = Employee.find(params[:id]) render json: { data: ActiveModelSerializers::SerializableReso urce.new(employee, serializer: EmployeeSerializer), message: ['Employee profile fetched successfully'], status: 200, type: 'Success'
  • 22. } end end end #app/controllers/v1/managers_controlle r.rb module V1 class ManagersController < ApplicationController def index managers = Manager.all.includes(:employees) render json: { data: ActiveModelSerializers::SerializableReso urce.new(managers, each_serializer: ManagerSerializer),
  • 23. message: ['Manager list fetched successfully'], status: 200, type: 'Success' } end def show manager = Manager.find(params[:id]) render json: { data: ActiveModelSerializers::SerializableReso urce.new(manager, serializer: ManagerSerializer), message: ['Manager profile fetched successfully'], status: 200, type: 'Success'
  • 24. } end end end The output for the request to fetch details of employees and managers APIs is as shown below. // GET http://localhost:3000/v1/employees/1 9. End-point Response
  • 28. We can extend the API and serializers by versioning them. For creating another version of the controller, create it under the path app/controllers/v2/employees_controlle r.rb And for creating the serializer, create it under the path app/serializers/v2/employee_serializer.r b. Remember that the class you’re creating for versioned API should fall under module V2 (or whatever version you’re defining for). 10. Versioning Controller & Serializer
  • 29. Created new project using rails new active-model-serializer --api Added required gems Defined models Migrated the schema Configured routes for the API Defined serializer for the respective model Implemented business logic in the controller Fetched data from API endpoints Quick Summary Here is the list of steps we performed to build serializer APIs:
  • 31. JSONAPI-RB- It is considered a highly performant and modular JSON:API. There's a vibrant community around it that has produced this Ruby library consisting of four micro-libraries and two frameworks. Fast JSON API- It is a lightning-fast JSON:API serializer for Ruby Objects. It is believed to be 25 times faster than Active Model Serializers. Blueprinter- It is a high-speed, declarative, and API agnostic serializer that uses composable views for reducing duplication.
  • 33. So, I hope you have a clear understanding of What is Active Model Serializers? Implementation, Usage, and Alternatives of Active Model Serializers in Rails 6. If you are looking for a helping hand in your Ruby on Rails project, then you’ve landed on the right page. Get in touch with us to hire ROR developer with the desired skillset at your ease and convenience.