SlideShare a Scribd company logo
Validation for APIs
Good validation practises. API focused.
Kirk Bushell
Who the hell am I?
• Technical Lead for Tectonic Digital (www.tectonic.com.au)
• Software architect for http://awardforce.com
• Technical writer (see: http://kirkbushell.me)
• Open source contributor (Laravel 3/4, various other projects)
• http://github.com/kirkbushell
• Also known as Oddman on IRC, forums.etc.
• @kirkbushell
Disclaimers
This is my first talk.
Sorry.
In addition...
• I'll assume you know a couple of things about validation and
• You know or at least understand some of the concepts of Laravel
4, including:
• Dependency injection and
• The IoC feature
• I start work at 4.30am (apologies if I'm not quite with it)
Why?
• There's been a lot of talk in the community the last 6 months
about validation
• How we can do it well - lots of different opinions
• I have a pretty strong opinion on this matter
What we're going to cover
• A brief history of MVC, the repository pattern and why validation
should be its own domain
• Implementing validation within an API context
• Using exceptions for greater readability
• Catching exceptions to generate API responses automagically
• The end result - cleaner code
What I'm not going to talk about
• RESTful APIs
• The view layer
A brief history of everything MVC.
• A blessing to web development (and software development in
general)
• Fat controllers, skinny models
• Skinny controllers, fat models
• Validation tied up in models (along with everything else)
• We still seem to be stuck on the previous point.
Introducing.. the repository pattern?
• Helped clean up models
• Query building and object management
• So, what about validation?
Validate all the things!
• Validation within models breaks the single responsibility principle
• Validation in models doesn't make much sense if you're using the
repository pattern
• Implemented via the controller or a service (such as a user
registration service)
Implementing validation
The validate method
Please read Jason Lewis' article: http://jasonlewis.me/article/laravel-
advanced-validation
// Validate function from article
protected function validate()
{
$this->validator = Validator::make($this->input, $this->rules);
if ($this->validator->fails())
{
throw new ValidateException($this->validator);
}
}
ValidateException
class ValidateException extends Exception
{
protected $validator;
public function __construct(Validator $validator)
{
$this->message = 'Validation has failed, or something.';
$this->validator = $validator;
}
public function getErrors()
{
return $this->validator->messages();
}
}
Our code, our rules
Implement our own custom rules for user registration:
// UserValidator class
class UserValidator extends Validator
{
public function register()
{
$this->rules = [
'email' => ['required', 'email'],
'password' => ['required']
];
$this->validate();
}
}
Validate!
Within our controller, load up our validator and validate the input.
// UserController
public function postRegister()
{
$input = Input::get();
App::make('UserValidator', [$input])->register();
return User::create($input);
}
Now what?
• When validation fails it will throw an exception:
if ($this->validator->fails())
{
throw new ValidateException($this->validator);
}
• We need to catch that exception and return a nice status code and
error message, along with any validation errors.
• Laravel 4 provides an excellent way of managing this.
Laravel 4 error handling
Create an error handler that is specific to validation exceptions:
App::error(function(ValidateException $exception)
{
$errorResponse = [
'message' => $exception->getMessage(),
'errors' => $exception->getErrors()
];
return Response::json($errorResponse, 422); // Unprocessable entity
});
In conclusion
• Complex validation should be in its own domain
• Helps to clean up our code, making it more readable
• Let the framework handle exceptions for you!
• Best for large applications (not so applicable to small apps)
Thank you.
You can catch me at the following online
locales:
• http://kirkbushell.me
• http://github.com/kirkbushell
• @kirkbushell

More Related Content

What's hot (20)

PPTX
Automated Acceptance Tests in .NET
Wyn B. Van Devanter
 
PDF
Agile Testing
Sargis Sargsyan
 
PPTX
Test Your Own Stuff - Scrum Atlanta 2015
Alex Kell
 
PPTX
BDD for APIs
Jason Harmon
 
PPTX
Automated Acceptance Tests & Tool choice
toddbr
 
PPTX
How to make your functional tests really quick
Mikalai Alimenkou
 
PPTX
BDD with SpecFlow and Selenium
Liraz Shay
 
PPTX
Better End-to-End Testing with Page Objects Model using Protractor
Kasun Kodagoda
 
PDF
Practical Tips & Tricks for Selenium Test Automation
Sauce Labs
 
PDF
Better Page Object Handling with Loadable Component Pattern - SQA Days 20, Be...
Sargis Sargsyan
 
PPTX
Cypress workshop for JSFoo 2019
Biswajit Pattanayak
 
PDF
Mastering UI automation at Scale: Key Lessons and Best Practices (By Fernando...
Applitools
 
PDF
How to Use Selenium, Successfully
Sauce Labs
 
PDF
Cypress - Best Practices
Brian Mann
 
PPTX
Introduction to cypress in Angular (Chinese)
Hong Tat Yew
 
PDF
Selenium Tips & Tricks
Dave Haeffner
 
PPTX
Beyond the Release: CI That Transforms Organizations
Sauce Labs
 
PDF
Automated Web Testing using JavaScript
Simon Guest
 
PPTX
Web automation with Selenium for software engineers
Mikalai Alimenkou
 
PPTX
Angular Unit Testing
Shailendra Chauhan
 
Automated Acceptance Tests in .NET
Wyn B. Van Devanter
 
Agile Testing
Sargis Sargsyan
 
Test Your Own Stuff - Scrum Atlanta 2015
Alex Kell
 
BDD for APIs
Jason Harmon
 
Automated Acceptance Tests & Tool choice
toddbr
 
How to make your functional tests really quick
Mikalai Alimenkou
 
BDD with SpecFlow and Selenium
Liraz Shay
 
Better End-to-End Testing with Page Objects Model using Protractor
Kasun Kodagoda
 
Practical Tips & Tricks for Selenium Test Automation
Sauce Labs
 
Better Page Object Handling with Loadable Component Pattern - SQA Days 20, Be...
Sargis Sargsyan
 
Cypress workshop for JSFoo 2019
Biswajit Pattanayak
 
Mastering UI automation at Scale: Key Lessons and Best Practices (By Fernando...
Applitools
 
How to Use Selenium, Successfully
Sauce Labs
 
Cypress - Best Practices
Brian Mann
 
Introduction to cypress in Angular (Chinese)
Hong Tat Yew
 
Selenium Tips & Tricks
Dave Haeffner
 
Beyond the Release: CI That Transforms Organizations
Sauce Labs
 
Automated Web Testing using JavaScript
Simon Guest
 
Web automation with Selenium for software engineers
Mikalai Alimenkou
 
Angular Unit Testing
Shailendra Chauhan
 

Viewers also liked (6)

PDF
WordPress: SEO
Pavel Karpov
 
PPTX
Repository design pattern in laravel - Samir Poudel
Sameer Poudel
 
PPTX
Нюансы создания интернет-магазина на WordPress
WordCamp Kyiv
 
PDF
WordPress: SEO. Ловим на живца.
Pavel Karpov
 
PDF
Ведение бизнеса на основе WordPress
Andrey Ovsyannikov
 
PDF
Object Oriented Design Principles
Thang Tran Duc
 
WordPress: SEO
Pavel Karpov
 
Repository design pattern in laravel - Samir Poudel
Sameer Poudel
 
Нюансы создания интернет-магазина на WordPress
WordCamp Kyiv
 
WordPress: SEO. Ловим на живца.
Pavel Karpov
 
Ведение бизнеса на основе WordPress
Andrey Ovsyannikov
 
Object Oriented Design Principles
Thang Tran Duc
 
Ad

Similar to Validation for APIs in Laravel 4 (9)

PDF
Comprehensive Validation with Laravel 4
Kirk Bushell
 
DOCX
Ultimate Laravel Performance Optimization Guide
CMARIX TechnoLabs
 
PPTX
Crafting beautiful software
Jorn Oomen
 
PPTX
Software Development with PHP & Laravel
Juan Victor Minaya León
 
PDF
Validations 101
Tom Ridge
 
PDF
Building RESTful APIs with Laravel A Complete Guide.pdf
Grey Space Computing
 
PDF
Form Validation in Flutter with Laravel Form Validation Syntax
RubenGray1
 
DOC
Wheels
guest9fd0a95
 
PPTX
Top 10 Expert Tips for Writing Clean & Maintainable Code in Laravel
e-Definers Technology
 
Comprehensive Validation with Laravel 4
Kirk Bushell
 
Ultimate Laravel Performance Optimization Guide
CMARIX TechnoLabs
 
Crafting beautiful software
Jorn Oomen
 
Software Development with PHP & Laravel
Juan Victor Minaya León
 
Validations 101
Tom Ridge
 
Building RESTful APIs with Laravel A Complete Guide.pdf
Grey Space Computing
 
Form Validation in Flutter with Laravel Form Validation Syntax
RubenGray1
 
Wheels
guest9fd0a95
 
Top 10 Expert Tips for Writing Clean & Maintainable Code in Laravel
e-Definers Technology
 
Ad

Recently uploaded (20)

PPTX
Introduction to Design of Machine Elements
PradeepKumarS27
 
PPTX
Green Building & Energy Conservation ppt
Sagar Sarangi
 
PPTX
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
PPTX
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
PPT
PPT2_Metal formingMECHANICALENGINEEIRNG .ppt
Praveen Kumar
 
PDF
Unified_Cloud_Comm_Presentation anil singh ppt
anilsingh298751
 
PPTX
Evaluation and thermal analysis of shell and tube heat exchanger as per requi...
shahveer210504
 
PDF
Design Thinking basics for Engineers.pdf
CMR University
 
PPTX
265587293-NFPA 101 Life safety code-PPT-1.pptx
chandermwason
 
DOCX
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
PDF
Zilliz Cloud Demo for performance and scale
Zilliz
 
PPTX
Heart Bleed Bug - A case study (Course: Cryptography and Network Security)
Adri Jovin
 
PPTX
Depth First Search Algorithm in 🧠 DFS in Artificial Intelligence (AI)
rafeeqshaik212002
 
PPTX
GitOps_Repo_Structure for begeinner(Scaffolindg)
DanialHabibi2
 
PPTX
Damage of stability of a ship and how its change .pptx
ehamadulhaque
 
PDF
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
DOCX
8th International Conference on Electrical Engineering (ELEN 2025)
elelijjournal653
 
PPTX
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
PDF
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
PPTX
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
Introduction to Design of Machine Elements
PradeepKumarS27
 
Green Building & Energy Conservation ppt
Sagar Sarangi
 
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
PPT2_Metal formingMECHANICALENGINEEIRNG .ppt
Praveen Kumar
 
Unified_Cloud_Comm_Presentation anil singh ppt
anilsingh298751
 
Evaluation and thermal analysis of shell and tube heat exchanger as per requi...
shahveer210504
 
Design Thinking basics for Engineers.pdf
CMR University
 
265587293-NFPA 101 Life safety code-PPT-1.pptx
chandermwason
 
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
Zilliz Cloud Demo for performance and scale
Zilliz
 
Heart Bleed Bug - A case study (Course: Cryptography and Network Security)
Adri Jovin
 
Depth First Search Algorithm in 🧠 DFS in Artificial Intelligence (AI)
rafeeqshaik212002
 
GitOps_Repo_Structure for begeinner(Scaffolindg)
DanialHabibi2
 
Damage of stability of a ship and how its change .pptx
ehamadulhaque
 
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
8th International Conference on Electrical Engineering (ELEN 2025)
elelijjournal653
 
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 

Validation for APIs in Laravel 4

  • 1. Validation for APIs Good validation practises. API focused. Kirk Bushell
  • 2. Who the hell am I? • Technical Lead for Tectonic Digital (www.tectonic.com.au) • Software architect for http://awardforce.com • Technical writer (see: http://kirkbushell.me) • Open source contributor (Laravel 3/4, various other projects) • http://github.com/kirkbushell • Also known as Oddman on IRC, forums.etc. • @kirkbushell
  • 4. This is my first talk.
  • 6. In addition... • I'll assume you know a couple of things about validation and • You know or at least understand some of the concepts of Laravel 4, including: • Dependency injection and • The IoC feature • I start work at 4.30am (apologies if I'm not quite with it)
  • 7. Why? • There's been a lot of talk in the community the last 6 months about validation • How we can do it well - lots of different opinions • I have a pretty strong opinion on this matter
  • 8. What we're going to cover • A brief history of MVC, the repository pattern and why validation should be its own domain • Implementing validation within an API context • Using exceptions for greater readability • Catching exceptions to generate API responses automagically • The end result - cleaner code
  • 9. What I'm not going to talk about • RESTful APIs • The view layer
  • 10. A brief history of everything MVC. • A blessing to web development (and software development in general) • Fat controllers, skinny models • Skinny controllers, fat models • Validation tied up in models (along with everything else) • We still seem to be stuck on the previous point.
  • 11. Introducing.. the repository pattern? • Helped clean up models • Query building and object management • So, what about validation?
  • 12. Validate all the things! • Validation within models breaks the single responsibility principle • Validation in models doesn't make much sense if you're using the repository pattern • Implemented via the controller or a service (such as a user registration service)
  • 14. The validate method Please read Jason Lewis' article: http://jasonlewis.me/article/laravel- advanced-validation // Validate function from article protected function validate() { $this->validator = Validator::make($this->input, $this->rules); if ($this->validator->fails()) { throw new ValidateException($this->validator); } }
  • 15. ValidateException class ValidateException extends Exception { protected $validator; public function __construct(Validator $validator) { $this->message = 'Validation has failed, or something.'; $this->validator = $validator; } public function getErrors() { return $this->validator->messages(); } }
  • 16. Our code, our rules Implement our own custom rules for user registration: // UserValidator class class UserValidator extends Validator { public function register() { $this->rules = [ 'email' => ['required', 'email'], 'password' => ['required'] ]; $this->validate(); } }
  • 17. Validate! Within our controller, load up our validator and validate the input. // UserController public function postRegister() { $input = Input::get(); App::make('UserValidator', [$input])->register(); return User::create($input); }
  • 18. Now what? • When validation fails it will throw an exception: if ($this->validator->fails()) { throw new ValidateException($this->validator); } • We need to catch that exception and return a nice status code and error message, along with any validation errors. • Laravel 4 provides an excellent way of managing this.
  • 19. Laravel 4 error handling Create an error handler that is specific to validation exceptions: App::error(function(ValidateException $exception) { $errorResponse = [ 'message' => $exception->getMessage(), 'errors' => $exception->getErrors() ]; return Response::json($errorResponse, 422); // Unprocessable entity });
  • 20. In conclusion • Complex validation should be in its own domain • Helps to clean up our code, making it more readable • Let the framework handle exceptions for you! • Best for large applications (not so applicable to small apps)
  • 22. You can catch me at the following online locales: • http://kirkbushell.me • http://github.com/kirkbushell • @kirkbushell