SlideShare a Scribd company logo
Test Driven APIs with Laravel
@michaelpeacock
What’s in store?
‱ Look at API concepts within Laravel
‱ Look at testing concepts within Laravel
‱ How we can gradually build an API with confidence in its functionality,
without ever opening an API client
@michaelpeacock
‱ Organiser of PHP North East
‱ Occasional author and speaker
‱ Freelance developer
‱ Consultant CTO for early stage SaaS start-ups
Laravel APIs
Lots for free
‱ Models & Collections > JSON Responses automatically
‱ Validation Failures > JSON Responses automatically
‱ Automatic handling of request and response headers (content-type,
etc)
Lots to of power to customise
‱ API Resources
‱ API Routing
‱ Resource Controllers
‱ API Resource Controllers
Laravel Tests
Database interaction
‱ RefreshDatabase: calls migrate:fresh (drops all tables and re-migrates)
‱ DatabaseTransactions: wraps test db calls in a transaction
HTTP Tests
Sample project
‱ API for user group
‱ Events
‱ Venues
‱ Talks
Model Integration Tests
Model integration tests
‱ A good starting point
‱ Give us confidence that models, migrations, relations and factories
are setup correctly
‱ Especially important if we are providing custom field names for
relations, or working with models outside of the root app directory
‱ Factories are important for API tests, so its good that we test the basis
setup before we move onto that.
‱ Inspired by Amo Chohan: 12 tried and tested top tips for better
testing
Key things to test initially
‱ We can instantiate the class
‱ Any relations
Test driven APIs with Laravel
Test driven APIs with Laravel
Test driven APIs with Laravel
Test driven APIs with Laravel
Migrations
Tip: Name your migrations well
Test driven APIs with Laravel
Models
Factories
Test driven APIs with Laravel
API Setup
Making requests
‱ $this->json(method, uri, data, headers)
‱ $this->getJson / postJson / patchJson / deleteJson
‱ $this->get(url, headers)
‱ $this->post(url, data, headers)
Testing responses: Status Codes
‱ $response->assertStatus(status code)
‱ $response->assertSuccessful()
‱ $response->assertOk()
‱ $response->assertNotFound()
‱ $response->assertNotFound()
‱ $response->assertForbidden()
GET /talks
Test driven APIs with Laravel
API Controllers
php artisan make:controller Api/EventsController --model=Event --api
API Routing
Test driven APIs with Laravel
Test driven APIs with Laravel
Testing response data
‱ $response->assertExactJson(array)
‱ $response->assertJson(array)
‱ $response->assertJsonCount(array)
‱ $response->assertJsonFragment(array)
‱ $response->assertJsonMissing(array)
‱ $response->assertJsonMissingExact(array)
‱ $response->assertJsonStructure(array)
Testing headers
‱ $response->assertHeader(header, value)
‱ $response->assertHeaderMissing(header)
‱ $response->assertLocation(url) // Location header
Lets check we get a JSON response

Test driven APIs with Laravel
Test driven APIs with Laravel
Test driven APIs with Laravel
Test driven APIs with Laravel
Better responses
‱ Venue name and description should be included
‱ Event id should not be included
‱ Start and end date should be formatted a specific way
Test driven APIs with Laravel
Test driven APIs with Laravel
Test driven APIs with Laravel
Test driven APIs with Laravel
Now we get some failing (not erroring) tests
Resources
php artisan make:resource Event
php artisan make:resource Venue
Test driven APIs with Laravel
Test driven APIs with Laravel
Passing tests again!
POST /events
‱ We now want to test creating an event
A test helper to build valid request data
Test driven APIs with Laravel
Test driven APIs with Laravel
Saving a new event
Status codes and Resources
Test driven APIs with Laravel
Testing Validation
‱ $response->assertJsonMissingValidationErrors(array)
‱ $response->assertJsonValidationErrors()
Test driven APIs with Laravel
Creating a new request
php artisan make:request CreateEventRequest
Test driven APIs with Laravel
Use the request
Test driven APIs with Laravel
Authenticating
actingAs
Thank you
‱ https://github.com/mkpeacock/talk-test-driven-apis-with-laravel

More Related Content

PDF
Laravelăźè‰Żă„ăšă“ă‚
 
PPTX
200 Days of Code, Beginner Track, Month 5
PDF
Building Scalable Applications with Laravel
PDF
Cassandra Summit 2014: Astyanax — To Be or Not To Be
PDF
Software Design Patterns in Laravel by Phill Sparks
PPTX
AlwaysOn Availability Group Job Management
PDF
Declaring Server App Components in Pure Java
ZIP
Continuous Integration For Rails Project
Laravelăźè‰Żă„ăšă“ă‚
 
200 Days of Code, Beginner Track, Month 5
Building Scalable Applications with Laravel
Cassandra Summit 2014: Astyanax — To Be or Not To Be
Software Design Patterns in Laravel by Phill Sparks
AlwaysOn Availability Group Job Management
Declaring Server App Components in Pure Java
Continuous Integration For Rails Project

What's hot (18)

PPT
Selenium course training institute ameerpet hyderabad – Best software trainin...
PDF
Modern Tools for API Testing, Debugging and Monitoring
PPTX
Introduction to PowerShell for SharePoint Admins and Developers - SharePoint ...
PDF
DAST in CI/CD pipelines using Selenium & OWASP ZAP
PPTX
Useful practices of creation automatic tests by using cucumber jvm
PDF
JSON API Standards
PDF
Knowing Laravel 5 : The most popular PHP framework
PDF
Continuous Delivery - Devoxx Morocco 2016
PDF
Continuous Delivery - Voxxed Days Thessaloniki 21.10.2016
PDF
New Theme Directory
PDF
Jumpstarting Testing In Your Organization with Selenium, Cucumber, & WebdriverIO
PPTX
What's New in Laravel 5 (Laravel Meetup - 23th Apr 15, Yogyakarta, ID)
PDF
Ebay legacy-code-retreat
PDF
Punta Dreamin 17 Generic Apex and Tooling Api
PPTX
Get Testing with tSQLt - SQL In The City Workshop 2014
PDF
Building a Cerberus App Without Losing Our Heads: The Passage to a Cross-Plat...
PDF
Karate, the black belt of HTTP API testing?
PPTX
Trailblazing ajmer ppt hands on with screen flow (11th july 2020)
Selenium course training institute ameerpet hyderabad – Best software trainin...
Modern Tools for API Testing, Debugging and Monitoring
Introduction to PowerShell for SharePoint Admins and Developers - SharePoint ...
DAST in CI/CD pipelines using Selenium & OWASP ZAP
Useful practices of creation automatic tests by using cucumber jvm
JSON API Standards
Knowing Laravel 5 : The most popular PHP framework
Continuous Delivery - Devoxx Morocco 2016
Continuous Delivery - Voxxed Days Thessaloniki 21.10.2016
New Theme Directory
Jumpstarting Testing In Your Organization with Selenium, Cucumber, & WebdriverIO
What's New in Laravel 5 (Laravel Meetup - 23th Apr 15, Yogyakarta, ID)
Ebay legacy-code-retreat
Punta Dreamin 17 Generic Apex and Tooling Api
Get Testing with tSQLt - SQL In The City Workshop 2014
Building a Cerberus App Without Losing Our Heads: The Passage to a Cross-Plat...
Karate, the black belt of HTTP API testing?
Trailblazing ajmer ppt hands on with screen flow (11th july 2020)
Ad

Similar to Test driven APIs with Laravel (20)

PDF
API Check Overview - Rigor Monitoring
PDF
Next-Level API Automation Testing Techniques – Part 1
KEY
Developer testing 101: Become a Testing Fanatic
PPTX
Reactive Programming and REST/JSON for SQL Databases - Microsoft SQL Server M...
PPTX
Test in Rest. API testing with the help of Rest Assured.
PPTX
API testing with the help of Rest Assured
PPTX
QA Fest 2019. ĐĐœĐœĐ° Đ§Đ”Ń€ĐœŃ‹ŃˆĐŸĐČа. Self-healing test automation 2.0. The Future
 
PDF
Workshop quality assurance for php projects - phpdublin
PDF
Efficient Rails Test Driven Development (class 3) by Wolfram Arnold
PDF
The Many Ways to Test Your React App
PDF
Python & Django TTT
PPTX
Api testing
PPTX
Coding Apps in the Cloud with Force.com - Part I
PPT
My experience in Software QA
PPTX
My Little Webap - DevOpsSec is Magic
PDF
5 levels of api test automation
PDF
JavaScript Fetch API
PPTX
Test in action – week 1
PDF
Leveraging Lucene/Solr as a Knowledge Graph and Intent Engine: Presented by T...
PDF
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
API Check Overview - Rigor Monitoring
Next-Level API Automation Testing Techniques – Part 1
Developer testing 101: Become a Testing Fanatic
Reactive Programming and REST/JSON for SQL Databases - Microsoft SQL Server M...
Test in Rest. API testing with the help of Rest Assured.
API testing with the help of Rest Assured
QA Fest 2019. ĐĐœĐœĐ° Đ§Đ”Ń€ĐœŃ‹ŃˆĐŸĐČа. Self-healing test automation 2.0. The Future
 
Workshop quality assurance for php projects - phpdublin
Efficient Rails Test Driven Development (class 3) by Wolfram Arnold
The Many Ways to Test Your React App
Python & Django TTT
Api testing
Coding Apps in the Cloud with Force.com - Part I
My experience in Software QA
My Little Webap - DevOpsSec is Magic
5 levels of api test automation
JavaScript Fetch API
Test in action – week 1
Leveraging Lucene/Solr as a Knowledge Graph and Intent Engine: Presented by T...
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
Ad

More from Michael Peacock (20)

PPTX
Immutable Infrastructure with Packer Ansible and Terraform
PPTX
Symfony Workflow Component - Introductory Lightning Talk
PPTX
Alexa, lets make a skill
PPTX
API Development with Laravel
PPTX
An introduction to Laravel Passport
PDF
Phinx talk
PDF
Refactoring to symfony components
PPT
Dance for the puppet master: G6 Tech Talk
PPT
Powerful and flexible templates with Twig
PPT
Introduction to OOP with PHP
KEY
Vagrant
KEY
Phpne august-2012-symfony-components-friends
KEY
Evolution of a big data project
PPTX
Real time voice call integration - Confoo 2012
PPTX
Dealing with Continuous Data Processing, ConFoo 2012
PPTX
Data at Scale - Michael Peacock, Cloud Connect 2012
PPTX
Supermondays twilio
PPTX
PHP & Twilio
PPTX
PHP Continuous Data Processing
PPTX
PHP North East Registry Pattern
Immutable Infrastructure with Packer Ansible and Terraform
Symfony Workflow Component - Introductory Lightning Talk
Alexa, lets make a skill
API Development with Laravel
An introduction to Laravel Passport
Phinx talk
Refactoring to symfony components
Dance for the puppet master: G6 Tech Talk
Powerful and flexible templates with Twig
Introduction to OOP with PHP
Vagrant
Phpne august-2012-symfony-components-friends
Evolution of a big data project
Real time voice call integration - Confoo 2012
Dealing with Continuous Data Processing, ConFoo 2012
Data at Scale - Michael Peacock, Cloud Connect 2012
Supermondays twilio
PHP & Twilio
PHP Continuous Data Processing
PHP North East Registry Pattern

Recently uploaded (20)

PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
top salesforce developer skills in 2025.pdf
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
System and Network Administration Chapter 2
PDF
AI in Product Development-omnex systems
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PPTX
CHAPTER 2 - PM Management and IT Context
PPTX
history of c programming in notes for students .pptx
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PPTX
ISO 45001 Occupational Health and Safety Management System
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
Nekopoi APK 2025 free lastest update
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
Digital Strategies for Manufacturing Companies
VVF-Customer-Presentation2025-Ver1.9.pptx
Design an Analysis of Algorithms II-SECS-1021-03
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
top salesforce developer skills in 2025.pdf
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
System and Network Administration Chapter 2
AI in Product Development-omnex systems
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Upgrade and Innovation Strategies for SAP ERP Customers
CHAPTER 2 - PM Management and IT Context
history of c programming in notes for students .pptx
Internet Downloader Manager (IDM) Crack 6.42 Build 41
ISO 45001 Occupational Health and Safety Management System
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Nekopoi APK 2025 free lastest update
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
How to Choose the Right IT Partner for Your Business in Malaysia
2025 Textile ERP Trends: SAP, Odoo & Oracle
Digital Strategies for Manufacturing Companies

Test driven APIs with Laravel

Editor's Notes

  • #8: Support for unit, browser, HTTP, console tests.
  • #10: Discuss how these work, and the impact on database transactions (i.e. how that works)
  • #16: Explain about the relationships first, putting thought into the modelling of the app. Emphasise how many times I've been caught out by a migration where it was linked to the wrong FK because I copy and pasted a migration!
  • #23: We can then iterate between tests and code, adding in the relationships that we need, until we get passing tests.
  • #38: Returning a collection or a model, combined with API request headers, results in the data being converted to JSON
  • #39: By default the JSON response includes all fields in the model, we can test that we have some fields that we want
  • #45: Error: date fields are not cast as dates, fix that, then get failing tests.
  • #47: Resources: transformers for our eloquent models
  • #54: Failing test because nothing is created, its an error not a fail as such because we called findOrFail, in our test, so our test has thrown an exception