Previous Next

Consuming APIs in Laravel (Ash Allen) (z-library.sk, 1lib.sk, z-lib.sk)

Author: Ash Allen

PHP

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!

📄 File Format: PDF
💾 File Size: 1.9 MB
11
Views
0
Downloads
0.00
Total Donations

📄 Text Preview (First 20 pages)

ℹ️

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

📄 Page 1
(This page has no text content)
📄 Page 2
Table of Contents Sponsor 11 ............................................................................................................................................ Introduction 12 .................................................................................................................................... About APIs 14 ....................................................................................................................................... What is an API? 15 ........................................................................................................................... Data Formats: JSON vs. XML 18 ....................................................................................................... JSON 18 ..................................................................................................................................... XML 21 ...................................................................................................................................... HTTP Message Structure 27 ............................................................................................................. Example HTTP Request Message 27 ......................................................................................... Example HTTP Response Message 29 ....................................................................................... Types of Web APIs 32 ....................................................................................................................... REST APIs 32 ............................................................................................................................. GraphQL APIs 43 ....................................................................................................................... RPC APIs 58 ............................................................................................................................... SOAP APIs 64 ............................................................................................................................. The Benefits of APIs 73 .................................................................................................................... Promotes Automation 73 .......................................................................................................... Improved Services 73 ............................................................................................................... Improved Security and Mitigation of Risk 74 ............................................................................. Encourages Innovation and Creativity 74 ................................................................................. Drawbacks of APIs 75 ....................................................................................................................... Building the Integration 75 .......................................................................................................
📄 Page 3
Rate Limiting 75 ........................................................................................................................ Security 76 ................................................................................................................................ Vendor Lock-In 76 ..................................................................................................................... Sending Sensitive Information 77 ............................................................................................. Authentication 78 ............................................................................................................................. Bearer Tokens 78 ...................................................................................................................... JSON Web Tokens (JWT) 80 ....................................................................................................... Basic Authentication 85 ............................................................................................................ API Integration Security 88 .............................................................................................................. Allowing Specific Domains or IP Addresses 88 .......................................................................... Avoiding Hardcoded API Keys 88 .............................................................................................. Granular Permissions 91 ........................................................................................................... Use HTTPS 92 ............................................................................................................................ Avoid Using API Keys in the URL 92 .......................................................................................... Conclusion 93 ................................................................................................................................... Code Techniques 94 ............................................................................................................................ Strict Type-Checking 95 ................................................................................................................... Should You Use Strict Types? 98 ............................................................................................... Composition Over Inheritance 100 ................................................................................................... Final Classes 105 ............................................................................................................................. Advantages of Final Classes 105 ............................................................................................... Disadvantages of Final Classes 107 .......................................................................................... Should You Use Final Classes? 114 ........................................................................................... Data Transfer Objects 116 ............................................................................................................... Readonly Classes and Properties 121 .............................................................................................. Using Interfaces and the Service Container 126 .............................................................................. Redacting Sensitive Parameters 132 ............................................................................................... Enums 135 .......................................................................................................................................
📄 Page 4
Benefits of Using Enums 135 .................................................................................................... Reducing Errors Using Enums 135 ............................................................................................ Adding Methods to Enums 138 ................................................................................................. Instantiating Enums from Values 140 ....................................................................................... Conclusion 142 ................................................................................................................................. Building an API Integration Using Saloon 143 ................................................................................ What is Saloon? 144 ......................................................................................................................... Alternatives to Saloon 145 ............................................................................................................... Guzzle 145 ................................................................................................................................ Http Facade 146 ........................................................................................................................ cURL 147 ................................................................................................................................... API SDK 149 .............................................................................................................................. Should I Use Saloon? 150 .......................................................................................................... Connectors, Requests, and Senders 152 .......................................................................................... Connectors 152 ......................................................................................................................... Requests 154 ............................................................................................................................ Senders 156 .............................................................................................................................. Installation and Configuration 158 ................................................................................................... Installing Saloon 158 ................................................................................................................. Configuration 158 ..................................................................................................................... Available Artisan Commands 160 .................................................................................................... saloon:connector 160 ................................................................................................................ saloon:request 160 ................................................................................................................... saloon:response 161 ................................................................................................................. saloon:plugin 161 ...................................................................................................................... saloon:auth 162 ........................................................................................................................ Preparing the API Integration 163 .................................................................................................... Building the Interface and Classes 164 ............................................................................................
📄 Page 5
Building the Interface 164 ......................................................................................................... Building the DTOs 166 .............................................................................................................. Building the Collections 169 ...................................................................................................... Creating the Integration Service Class 170 ............................................................................... Binding the Interface to the Concrete Implementation 172 ...................................................... Preparing the Connector 174 ........................................................................................................... Creating the Connector Class 174 ............................................................................................. Adding the Connector to the Service Class 176 ........................................................................ Authentication 178 ........................................................................................................................... Where to Use Authentication 178 ............................................................................................. Types of Authentication 180 ..................................................................................................... Sending Requests 185 ..................................................................................................................... Fetching a Single Resource 185 ................................................................................................ Fetching a List of Resources 192 .............................................................................................. Creating a New Resource 195 ................................................................................................... Updating an Existing Resource 199 .......................................................................................... Deleting a Resource 202 ........................................................................................................... Pagination 205 ................................................................................................................................. Understanding Paginated Responses 205 ................................................................................. Sending Requests to Paginated Endpoints in Saloon 209 ......................................................... Sending the Requests to the API 216 ........................................................................................ Solo Requests in Saloon 221 ............................................................................................................ Sending Concurrent Requests 224 ................................................................................................... Sequential vs. Concurrent Requests 224 .................................................................................. Sending Concurrent Requests 228 ............................................................................................ Middleware 232 ................................................................................................................................ Using the Connector's "boot" Method 232 ................................................................................ Using Closures 233 ................................................................................................................... Using Invokable Classes 235 .....................................................................................................
📄 Page 6
Plugins 238 ...................................................................................................................................... AcceptsJson 238 ........................................................................................................................ AlwaysThrowOnError 239 .......................................................................................................... HasTimeout 239 ........................................................................................................................ Error Handling 241 ........................................................................................................................... Saloon's Exceptions 241 ........................................................................................................... Manually Handling Errors 242 ................................................................................................... Automatically Handling Errors 244 ............................................................................................ Using Your Own Exceptions 244 ................................................................................................ Changing the Exception Logic 251 ............................................................................................ Retrying Requests 253 ..................................................................................................................... Retry a Request 253 ................................................................................................................. Customize the Retry Logic 254 ................................................................................................. Handling API Rate Limits 256 ........................................................................................................... What is Rate Limiting? 256 ....................................................................................................... Strategies for Working with Rate Limited APIs 257 ................................................................... Installing the Saloon Rate Limit Plugin 259 ............................................................................... Configuring the Rate Limits 259 ................................................................................................ Sending the Requests 265 ........................................................................................................ Catching 429 Error Responses 269 ........................................................................................... Setting Your Own Rate Limit Thresholds 270 ............................................................................ Caching Responses 271 ................................................................................................................... Installing the Cache Plugin 271 ................................................................................................. How to Cache Responses 272 ................................................................................................... Disabling and Invalidating the Cache 274 ................................................................................. Testing API Integrations 276 ............................................................................................................ Benefits of Testing 276 ............................................................................................................. Should We Make Real Requests? 278 ....................................................................................... What Should We Test? 281 .......................................................................................................
📄 Page 7
Using a Test Double 283 ........................................................................................................... Extracting Test Helpers Into Traits 289 ..................................................................................... Adding Assertions to Your Test Double 292 .............................................................................. Mocking HTTP Responses 300 ................................................................................................... Recording HTTP Responses 307 ................................................................................................ Conclusion 312 .......................................................................................................................... OAuth 313 ............................................................................................................................................. What is OAuth? 314 ......................................................................................................................... Use Cases for OAuth 315 ................................................................................................................. Single-Sign-On (SSO) 315 ......................................................................................................... Third-Party API Access 315 ....................................................................................................... Authenticating on Smart Devices 315 ....................................................................................... Server-to-Server Authorization 316 ........................................................................................... OAuth Terminology 317 ................................................................................................................... OAuth Roles 317 ....................................................................................................................... Flows and Grants 317 ............................................................................................................... Tokens 318 ............................................................................................................................... Client ID and Client Secret 318 ................................................................................................. Public and Confidential Clients 319 ........................................................................................... Scopes 320 ............................................................................................................................... OAuth 2.0 Flows 321 ........................................................................................................................ Authorization Code Grant 321 ................................................................................................... Authorization Code Grant with PKCE 324 .................................................................................. Refresh Token Grant 328 .......................................................................................................... Client Credentials Grant 331 ..................................................................................................... Device Code Grant 333 ............................................................................................................. Implicit Grant 337 ..................................................................................................................... Resource Owner Password Grant 340 .......................................................................................
📄 Page 8
The Benefits of Using OAuth 342 ..................................................................................................... Improved Security 342 .............................................................................................................. Improved User Experience 342 ................................................................................................. Common and Well-Supported Standard 343 ............................................................................. View and Revoke Access 343 .................................................................................................... The Drawbacks of Using OAuth 344 ................................................................................................. Complexity 344 ......................................................................................................................... Security Concerns 344 .............................................................................................................. Third-Party Dependency 344 .................................................................................................... Potential for Inconsistent Implementations 345 ........................................................................ Possible Alienation of Users 345 ............................................................................................... OAuth Best Practices 346 ................................................................................................................. Use PKCE with the Authorization Code Flow 346 ....................................................................... Don't Use the Password Grant 346 ........................................................................................... Use the Authorization Code Flow Instead of the Implicit Flow 347 ............................................ Use Exact String Matching for Redirect URIs 347 ...................................................................... Don't Use Access Tokens in Query Strings 348 ......................................................................... Use Sender-Constrained or One-Time Use Refresh Tokens 348 ................................................ Allow Users to Revoke Access 350 ............................................................................................ Pass Credentials in the Authorization Header 350 .................................................................... Laravel Packages for OAuth 352 ...................................................................................................... Laravel Socialite 352 ................................................................................................................. Laravel Passport 353 ................................................................................................................. OAuth2 with Saloon — Authorization Code Grant 354 ..................................................................... Preparing the OAuth Integration 354 ........................................................................................ Creating the OAuth Routes 355 ................................................................................................ Preparing Your Connector For OAuth 356 ................................................................................. Building the Interface and Classes 360 ..................................................................................... Building the DTOs and Collection 361 .......................................................................................
📄 Page 9
Preparing Our Model and Database 365 ................................................................................... Creating the Integration Service Class 370 ............................................................................... Binding the Interface to the Concrete Implementation 371 ...................................................... Generating an Authorization URL 371 ....................................................................................... Handling the Authorization Callback 375 .................................................................................. Making a Request Using the Access Token 382 ........................................................................ Testing Your OAuth2 Integrations 387 ............................................................................................. Preparing For Testing 388 ......................................................................................................... Testing the Controllers 389 ....................................................................................................... Testing the Service Class 401 ................................................................................................... Conclusion 411 ................................................................................................................................. Webhooks 412 ...................................................................................................................................... What Are Webhooks? 413 ................................................................................................................ The Advantages of Webhooks 415 ................................................................................................... Real-Time Updates 415 ............................................................................................................. Reduced Load on Your Application 415 ..................................................................................... Seamless Integrations With Your Application 416 ..................................................................... The Disadvantages of Webhooks 417 .............................................................................................. Increased Complexity 417 ........................................................................................................ Increased Security Risks 417 .................................................................................................... Fire and Forget 417 ................................................................................................................... Defining Webhooks Routes 419 ....................................................................................................... Defining Webhook Routes in the External Application's Dashboard 419 ................................... Defining Webhook Routes at Runtime 420 ............................................................................... Building Webhook Routes 422 ......................................................................................................... What Will Be Sent 423 .............................................................................................................. Creating the Route 424 ............................................................................................................. Creating the Enum 426 .............................................................................................................
📄 Page 10
Creating the Model 427 ............................................................................................................. Creating the Controller 428 ....................................................................................................... Webhook Security 431 ..................................................................................................................... Why You Must Secure Your Webhooks 431 ............................................................................... Validating a Mailgun Webhook 432 ........................................................................................... Testing Webhook Routes 437 .......................................................................................................... Using Queues to Process Webhooks 441 ......................................................................................... Benefits of Processing Webhooks Using Queues 441 ................................................................ Creating a New Job Class 444 ................................................................................................... Updating the Controller 447 ...................................................................................................... Updating the Tests 448 ............................................................................................................. Conclusion 454 ................................................................................................................................. Final Words 455 ...................................................................................................................................
📄 Page 11
11 Sponsor Discover the Future of API Analysis API Insights isn't just another tool; it's a game-changer in API schema analysis. We delve deep into three critical aspects of your API - Performance, Design, and Security - providing you with invaluable insights and a comprehensive evaluation. 1. Security, Your Top Priority Our proprietary tests go beyond the surface to unearth potential security risks. We identify vulnerabilities like API Key Exposure, Cyclical ID Attack Risks, and IDOR Risks. With API Insights, you not only have a tool to help ensure the security of your API but also safeguard the data it handles. 2. Performance Excellence A high-performing API leads to satisfied customers. We evaluate your API's performance using cutting- edge techniques. From inspecting headers in a single GET request, we are assessing Caching, CDN Usage, and HTTP/2 or HTTP/3 utilization, we leave no stone unturned. Expect a faster and more stable API if you implement our insights. 3. Design Matters Good design is at the heart of every successful API. API Insights evaluates how well your schema serves developers' needs and how effectively your API is designed. We scrutinize aspects such as error code handling, Personally Identifiable Information (PII) risks, language consistency, and parameter and endpoint descriptions. Ready to revolutionize your API Schema experience? Visit apiinsights.io today to harness the full potential of this 100% free tool.
📄 Page 12
12 Introduction Hey! My name is Ash Allen, and I'm a freelance Laravel web developer based in the United Kingdom. Over the past five years, I've worked on many projects that range from websites for small, local businesses to large-scale enterprise applications for large companies. During this time, I've been lucky enough to work with fantastic people and companies and learned a lot from them. I've also worked on interesting projects and seen how different teams tackle different problems. If there's one thing I've noticed during this time, it's that most web applications eventually integrate with an external API. Whether this is for simple things such as sending emails or more complex things such as integrating with a third-party payment gateway, being able to lean on external systems to do the heavy lifting for you can significantly benefit your application. It can allow you to focus on the core features of your application and let external companies handle things you don't need to (and don't want to) worry about. For example, instead of building a payment system for your new web application, you can use Stripe to handle payments. This lets you focus more on building cool new features and have Stripe worry about payment processing. I've worked with many different APIs, including Stripe, Mailgun, Twilio, Marketo, Zapier, Twitter, Vonage, GitHub, and many more. While working with these APIs, I've noticed common patterns and best practices that I (or the team I'm working with) have been able to use. I've also seen mistakes and oversights that came back to bite us later on. In this book, we will cover the techniques I've learned and give you a better understanding of how to consume APIs directly from your Laravel application. We'll start by covering what APIs are, the benefits they provide, the different types of APIs that you might come across, and how to authenticate with them. We'll then cover code techniques I use to make consuming APIs easier. We'll discuss things like final classes, readonly classes and properties, composition over inheritance, interfaces, data transfer objects, and more. After this, we'll cover how to consume an API from your Laravel application using Saloon. We'll discuss things like making requests, OAuth2, caching responses, error handling, and testing your API integrations.
📄 Page 13
13 Finally, we'll move on to cover webhooks. We'll discuss what they are, how to set them up, and how to securely handle them in your Laravel application. By the end of this book, you should have an excellent understanding of how to consume APIs directly from your Laravel application using maintainable, testable, and extensible code. You should be confident in your ability to integrate with third-party APIs and able to do so in a secure and robust way.
📄 Page 14
14 About APIs Before writing any code, we must understand some things about APIs. This chapter will cover what APIs are, the different types of APIs you might come across, and the benefits and drawbacks of consuming APIs in your web applications. We'll also cover common data formats you'll encounter in APIs. We'll then cover different types of authentication and API integration security best practices. By the end of this chapter, you should understand how APIs can be used in your Laravel applications and have a good foundation for the rest of the book.
📄 Page 15
15 What is an API? Essentially, APIs (application programming interfaces) are a way for systems to communicate with each other. They allow you to build integrations with systems and services to offer your users more features. They are typically used to send and receive data without needing to know a system's inner workings. This allows you to focus on building the core of your system and letting other people build specialized features. For example, you might use a third-party payment system such as Stripe to handle payments. This means you don't need to worry about many of the complexities of handling payments, such as PCI (payment card industry) compliance, because they handle storing card details. Another example of using an API in your application may be using HubSpot to manage your clients. You could use the HubSpot API to create a new contact in HubSpot when a user signs up for your website's newsletter or fills out a contact form. This would allow you to keep your client data in one place and make them easier to manage. You may also use an API as part of your application's authentication and authorization process. For example, you can allow users to sign in to your application using their Google account. To do this, you could use the Google API to authenticate the user and retrieve their details (such as their name, email address, profile picture, etc.). You've likely seen this before when signing into an application and being presented with options such as "Sign in with Google" or "Sign in with Facebook". The following diagram shows the high-level flow of how you can send API requests to an external system and receive a response:
📄 Page 16
16 Depending on the types of Laravel projects you work on, you may have already interacted with external APIs without realizing it. Here are some common APIs that you may have already worked with and possible use cases for them: Stripe - Payment processing Mailgun - Sending emails Mailchimp - Email marketing Twilio - SMS messaging Vonage - SMS messaging Facebook - Social media post scheduling Twitter - Social sign in Instagram - Social sign in Google - Social sign in and cloud storage (Google Drive) GitHub - Accessing repositories and user data AWS- Cloud storage (S3) As well as using APIs to communicate with external systems, they can be used to communicate between internal systems. For example, imagine you have an e-commerce website that is split into two separate applications: A customer-facing website for viewing products and placing orders. An admin panel for employees to manage the stock and orders. Your admin panel may display some statistics from the customer-facing website. To do this, you could create an API on the customer-facing website that returns the statistics. The admin panel could then make a request to the website's API to retrieve the statistics and display them. This means the admin panel doesn't need to know how the customer-facing website works; it just needs to know how to make a request to the API. This allows you to keep the two systems separate and makes it easier to maintain them. If you were to change how the customer-facing website works, you wouldn't need to change the admin panel because it only interacts with the API. This is a great example of how APIs can be used to communicate between internal systems while abstracting away the system's inner workings. You may also not want the customer-facing website's API publicly accessible, so you could make it private and only allow requests from the admin panel.
📄 Page 17
17 The following diagram shows the high-level flow of how you can send API requests between the two systems:
📄 Page 18
18 Data Formats: JSON vs. XML This book will focus on consuming APIs that accept JSON as the request body and return JSON as the response body. However, it's important to be aware that there are other types of data formats that can be used, such as XML. Although you'll most likely work with APIs in your Laravel applications that use JSON, you may sometimes need to consume XML APIs. Let's look at the difference between JSON and XML and the pros and cons of each. JSON JavaScript Object Notation (JSON) is a lightweight format that can be used for structuring data. Generally, it can be easy to read and write in PHP, so it's a format you'll often come across. In your Laravel applications, you may see JSON being used for things such as: API response bodies (whether the response is sent from or to your application). API request bodies (whether the response is sent from or to your application). Storing translations in your application (e.g., resources/lang/en.json). JSON supports a limited amount of data types, such as strings, numbers, booleans, arrays, and objects. Let's take a look at an example of some JSON data that makes use of each of these data types:
📄 Page 19
19 { "name": "John Doe", "email": "john.doe@example.com", "phone": "555-123-4567", "approved": true, "age": 27, "hobbies": [ "golf", "tennis", "football" ], "address": { "street": "123 Main Street", "city": "New York", "state": "NY", "zip": "10001" } } Let's break down the JSON structure above: At the top level of the object, the name, email, and phone fields are all strings. The approved field is a boolean. The age field is a number. The hobbies field is an array of strings. The address field is an object that contains the street, city, state, and zip strings fields. Advantages of JSON Now that we understand what JSON is, let's look at some of the benefits of using JSON. Easy to Read and Write Although data structures like JSON are usually intended to be written and read programmatically, you'll often find that you'll need to read them yourself. You may want to do this to inspect the
📄 Page 20
20 structure of an API response or to add a new field to a config file. Due to JSON's simple syntax and format, it's generally human-friendly and can be easy to read and write. This can make it easier to work with than other data formats, such as XML. Smaller Request, Response and File Sizes As a result of JSON's lightweight format, it can often result in smaller request, response, and file sizes when compared to other formats, such as XML. Request and response sizes may not be important for smaller applications, but they can become a problem for larger applications that handle a lot of traffic and need to be efficient. Keeping the response sizes as small as possible reduces the chance of exceeding bandwidth limits and improves response times. Native Support in JavaScript A huge benefit of using JSON is that JavaScript natively supports it and can be easily parsed by it. This makes it easy to pass data from your Laravel Blade views straight into your JavaScript code or make API requests to external services from your JavaScript files, among other things. Widely Adopted JSON is a widely adopted format, which means you'll come across it quite often. As a result, it can be easy to find documentation and examples of how to work with it. This can make it easier to start using the format and consuming APIs that use it because the syntax is something you'll be familiar with. Disadvantages of JSON Although JSON is a great format, it has some disadvantages that you should be aware of. No Support for Comments As JSON objects grow in size and complexity, you may want to add comments to explain what a particular field is used for. You may particularly want to do this if you're using JSON to define a config file for your application.
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now

Recommended for You

Loading recommended books...
Failed to load, please try again later
Back to List