As we upgrade our open source SendGrid API libraries to support our v3 Web API, we’ve also been updating our API client libraries to contain as few dependencies as possible. Part of this effort entails creating brand new, lean HTTP clients to drive communication with our APIs. The last HTTP client I wrote about was Python, and in this post, we’ll explore our new PHP HTTP client that will drive our new v5 SendGrid PHP library, using a working prototype.
The remainder of this post will reference the following code:
A fluent interface allows us to create API calls dynamically, without having to pre-define every endpoint. For example, we can use `$client->path()->to()->the()->endpoint()->get()` for a call to: `GET /path/to/the/endpoint` without defining methods for `path`, `to`, `the` and `endpoint`.
Generally, we simply return `$this` when chaining our method calls together. However, in this case we are returning a new version of the `Fluent` object, because we want to preserve fragments of the URL for later reuse see line 11.
Handling Special Cases
To handle special cases or to allow users to specify a complete path as a string, we use the `_()` method see line 9. You pass in a string and receive a new object with the name of your string added to the URL path variable.
References & Acknowledgements
After I completed the Python implementation of a fluent interface, the next day, Matt came up with a working prototype of the PHP version. Yes, he’s got PHP skillz to pay the billz. You can check out Matt’s post about the developer experience at SendGrid, Using DX to Solve Your Next Email Apocalypse.
The following references helped me understand the concepts described in this post:
Thank you for dropping by, and if you decide to build something with this library or have some contributions, please open an issue in our GitHub repo.
What’s next? Stay tuned as we continue to release similar blog posts for each the other languages we support, like Ruby, C#, Node.js, Go and Java. To start testing your email and integration, sign up for a free SendGrid account today.