Consuming APIs in Laravel

This document was uploaded by one of our users. The uploader already confirmed that they had the permission to publish it. If you are author/publisher or own the copyright of this documents, please report to us by using this DMCA report form.

Simply click on the Download Book button.

Yes, Book downloads on Ebookily are 100% Free.

Sometimes the book is free on Amazon As well, so go ahead and hit "Search on Amazon"

Learn how to confidently integrate third-party APIs in your Laravel projects using maintainable, testable and extensible code.The world of APIs has finally been made simple! You've built a great app, but now your users want more power. Maybe they want their monthly reports to be sent to their accounting software. Perhaps they need to automatically create new tasks in their project management tool, or they want contact form submissions to be automatically sent to their CRM. There’s no doubt that integrating with third-party APIs and adding these features to your app is a great way to add value for your users , but it can also be super daunting to get started… In fact, I’d go as far as to say API integrations are one of the most complex and scary things I’ve faced in my entire developer career! There are just so many things you’ve got to know if you want your API integration to work properly and be robust, secure and easy to maintain. If your client or boss uttering the words “we need it to integrate with XYZ’s API” gives you nightmares, you’re certainly not alone. What’s more, once you’ve started building your integration, it’s difficult to know how to write automated tests for your code. After all, creating an API integration without writing tests is a surefire way to build an integration that has bugs and is difficult to maintain. But even more frustrating is the fact it’s also just so damn hard to find reliable information you can trust . Take a look online and you’ll come across a huge amount of info about APIs that’s either completely outdated or just plain wrong. If you’ve ever done any research yourself, you’ll know it’s often near impossible to know what’s still relevant, or exactly how some of the concepts you’re learning are supposed to fit into your application. Theory is great - but what you really need is actionable information from someone who knows the subject inside out… And that’s exactly what I’m offering you today . It’s the comprehensive API manual I wish I had when I started out as a developer. One you can trust and will want to refer back to again and again. Introducing Consuming APIs in Laravel, your complete guide to confidently building robust and powerful API integrations in your Laravel projects to add cool new features. Whether you’re an experienced pro or just starting out in your developer career, it includes all the information you need to consume APIs directly from your Laravel application using maintainable, testable, and extensible code. Inside, you’ll get instant access to over 440-pages of detailed yet easy-to-digest information with tons of real-world code examples you can start applying to your projects straight away. Finally you can easily integrate third-party APIs with your Laravel project and feel confident in doing so! Books emoji What's Covered in the Book? The book aims to help you build powerful API integrations that are testable, maintainable, and easy to understand . I'll show you the way I've built integrations for many projects that help my clients and their users, including specific code examples that give context as to exactly where, why, and how you’d use something in your Laravel app… Something I’ve found to be sorely lacking in many other books and tutorials I’ve read on the subject. We'll cover techniques that we can use to improve the quality of API integration code . We'll look at how we can use these techniques to integrate with real-world APIs using Saloon. We'll cover how to write tests for your API integrations, how to handle rate limits, and how to deal with errors . When I started writing the book, one of my main aims was to really hone in on the areas that developers often find particularly confusing. For example, I’ve included a whole chapter on OAuth , which is a complex topic that people are often scared of going anywhere near, so I finally wanted to make it super understandable and less nightmarish! It contains diagrams and step-by-step instructions on how each “OAuth flow” works. I’ve also added a full guide on how you can use Saloon in your Laravel applications to interact with an OAuth API . I’m really hoping that this section makes developers less scared of OAuth and encourages them to feel more confident and comfortable using it. There’s also a dedicated section on securely handling webhooks sent from third-party APIs back to your application. I’ve worked on many projects where the developers haven’t written secure code for handling the webhooks, which has meant that there have been security vulnerabilities in the systems that could be exploited. Using code examples, I’ll show you exactly how to securely handle webhooks and make your API integration more robust and bulletproof. In my experience, it’s information like this that is pure gold when it comes to becoming more competent and confident with handling APIs. Throughout, I’ve really tried hard to break down a lot of the barriers and make everything super simple for you to dive right in with confidence and make your Laravel projects even more awesome! Making API Requests You'll learn how to make requests to third-party API integrations using Saloon. Securely Handling Webhooks Discover how to securely handle webhooks sent from third-party APIs back to your Laravel application. Testing Master how to write tests for your API integrations to prove they work as expected. Caching Responses You'll learn how to cache responses from third-party APIs to reduce the number of requests you make and improve your application's performance. Working with Rate Limits You'll uncover techniques that you can use to avoid hitting rate limits when making requests to third-party APIs. Handling Errors Learn different ways to effectively handle errors that occur when making requests using your API integration. Understand OAuth Discover exactly how to use OAuth to authenticate with third-party applications (such as GitHub) directly from your Laravel applications. Robust Code Practices You'll learn several techniques that you can use to improve the quality of your API integration code, such as data transfer objects, read-only classes and properties, strict type checking, and more. Learn About APIs You'll fully understand APIs, how they work, and the benefits they can provide for businesses.

Author(s): Ashley Allen
Publisher: Independently published
Year: 2023

Language: English
Pages: 455

Consuming APIs in Laravel
Sponsor
Discover the Future of API Analysis
1. Security, Your Top Priority
2. Performance Excellence
3. Design Matters
Introduction
About APIs
What is an API?
Data Formats: JSON vs. XML
JSON
XML
HTTP Message Structure
Example HTTP Request Message
Example HTTP Response Message
Types of Web APIs
REST APIs
GraphQL APIs
RPC APIs
SOAP APIs
The Benefits of APIs
Promotes Automation
Improved Services
Improved Security and Mitigation of Risk
Encourages Innovation and Creativity
Drawbacks of APIs
Building the Integration
Rate Limiting
Security
Vendor Lock-In
Sending Sensitive Information
Authentication
Bearer Tokens
JSON Web Tokens (JWT)
Basic Authentication
API Integration Security
Allowing Specific Domains or IP Addresses
Avoiding Hardcoded API Keys
Granular Permissions
Use HTTPS
Avoid Using API Keys in the URL
Conclusion
Code Techniques
Strict Type-Checking
Should You Use Strict Types?
Composition Over Inheritance
Final Classes
Advantages of Final Classes
Disadvantages of Final Classes
Should You Use Final Classes?
Data Transfer Objects
Readonly Classes and Properties
Using Interfaces and the Service Container
Redacting Sensitive Parameters
Enums
Benefits of Using Enums
Reducing Errors Using Enums
Adding Methods to Enums
Instantiating Enums from Values
Conclusion
Building an API Integration Using Saloon
What is Saloon?
Alternatives to Saloon
Guzzle
Http Facade
cURL
API SDK
Should I Use Saloon?
Connectors, Requests, and Senders
Connectors
Requests
Senders
Installation and Configuration
Installing Saloon
Configuration
Available Artisan Commands
saloon:connector
saloon:request
saloon:response
saloon:plugin
saloon:auth
Preparing the API Integration
Building the Interface and Classes
Building the Interface
Building the DTOs
Building the Collections
Creating the Integration Service Class
Binding the Interface to the Concrete Implementation
Preparing the Connector
Creating the Connector Class
Adding the Connector to the Service Class
Authentication
Where to Use Authentication
Types of Authentication
Sending Requests
Fetching a Single Resource
Fetching a List of Resources
Creating a New Resource
Updating an Existing Resource
Deleting a Resource
Pagination
Understanding Paginated Responses
Sending Requests to Paginated Endpoints in Saloon
Sending the Requests to the API
Solo Requests in Saloon
Sending Concurrent Requests
Sequential vs. Concurrent Requests
Sending Concurrent Requests
Middleware
Using the Connector's "boot" Method
Using Closures
Using Invokable Classes
Plugins
AcceptsJson
AlwaysThrowOnError
HasTimeout
Error Handling
Saloon's Exceptions
Manually Handling Errors
Automatically Handling Errors
Using Your Own Exceptions
Changing the Exception Logic
Retrying Requests
Retry a Request
Customize the Retry Logic
Handling API Rate Limits
What is Rate Limiting?
Strategies for Working with Rate Limited APIs
Installing the Saloon Rate Limit Plugin
Configuring the Rate Limits
Sending the Requests
Catching 429 Error Responses
Setting Your Own Rate Limit Thresholds
Caching Responses
Installing the Cache Plugin
How to Cache Responses
Disabling and Invalidating the Cache
Testing API Integrations
Benefits of Testing
Should We Make Real Requests?
What Should We Test?
Using a Test Double
Extracting Test Helpers Into Traits
Adding Assertions to Your Test Double
Mocking HTTP Responses
Recording HTTP Responses
Conclusion
OAuth
What is OAuth?
Use Cases for OAuth
Single-Sign-On (SSO)
Third-Party API Access
Authenticating on Smart Devices
Server-to-Server Authorization
OAuth Terminology
OAuth Roles
Flows and Grants
Tokens
Client ID and Client Secret
Public and Confidential Clients
Scopes
OAuth 2.0 Flows
Authorization Code Grant
Authorization Code Grant with PKCE
Refresh Token Grant
Client Credentials Grant
Device Code Grant
Implicit Grant
Resource Owner Password Grant
The Benefits of Using OAuth
Improved Security
Improved User Experience
Common and Well-Supported Standard
View and Revoke Access
The Drawbacks of Using OAuth
Complexity
Security Concerns
Third-Party Dependency
Potential for Inconsistent Implementations
Possible Alienation of Users
OAuth Best Practices
Use PKCE with the Authorization Code Flow
Don't Use the Password Grant
Use the Authorization Code Flow Instead of the Implicit Flow
Use Exact String Matching for Redirect URIs
Don't Use Access Tokens in Query Strings
Use Sender-Constrained or One-Time Use Refresh Tokens
Allow Users to Revoke Access
Pass Credentials in the Authorization Header
Laravel Packages for OAuth
Laravel Socialite
Laravel Passport
OAuth2 with Saloon — Authorization Code Grant
Preparing the OAuth Integration
Creating the OAuth Routes
Preparing Your Connector For OAuth
Building the Interface and Classes
Building the DTOs and Collection
Preparing Our Model and Database
Creating the Integration Service Class
Binding the Interface to the Concrete Implementation
Generating an Authorization URL
Handling the Authorization Callback
Making a Request Using the Access Token
Testing Your OAuth2 Integrations
Preparing For Testing
Testing the Controllers
Testing the Service Class
Conclusion
Webhooks
What Are Webhooks?
The Advantages of Webhooks
Real-Time Updates
Reduced Load on Your Application
Seamless Integrations With Your Application
The Disadvantages of Webhooks
Increased Complexity
Increased Security Risks
Fire and Forget
Defining Webhooks Routes
Defining Webhook Routes in the External Application's Dashboard
Defining Webhook Routes at Runtime
Building Webhook Routes
What Will Be Sent
Creating the Route
Creating the Enum
Creating the Model
Creating the Controller
Webhook Security
Why You Must Secure Your Webhooks
Validating a Mailgun Webhook
Testing Webhook Routes
Using Queues to Process Webhooks
Benefits of Processing Webhooks Using Queues
Creating a New Job Class
Updating the Controller
Updating the Tests
Conclusion
Final Words