DEV Community

Cover image for Introducing FetchPHP: A Simple, Powerful HTTP Library for PHP, Inspired by JavaScript’s fetch API
Jerome Thayananthajothy
Jerome Thayananthajothy

Posted on • Updated on

Introducing FetchPHP: A Simple, Powerful HTTP Library for PHP, Inspired by JavaScript’s fetch API

Hey PHP developers! 👋

Today, I’m excited to introduce FetchPHP, a lightweight HTTP library for PHP that takes direct inspiration from JavaScript’s fetch API. If you’ve ever found yourself making HTTP requests in PHP and thinking "I wish this was as simple as JavaScript’s fetch," then this package is for you!

💡 What is FetchPHP?

FetchPHP is a new, modern HTTP library built on top of Guzzle, designed to make working with HTTP requests in PHP both simple and powerful. Just like its JavaScript inspiration, FetchPHP allows you to send asynchronous or synchronous requests, easily handle JSON, multipart, or form data, and comes with built-in status helpers to make handling responses a breeze.

✨ Key Features

Here’s a quick overview of the features FetchPHP brings to the table:

  • Synchronous and Asynchronous Support: You can choose between fetch (synchronous) and fetchAsync (asynchronous), giving you flexibility based on your needs.
  • Familiar API: If you’re used to JavaScript’s fetch API, you’ll feel right at home. FetchPHP’s API mirrors that simplicity and ease of use.
  • Support for JSON, Multipart, and Form Data: Easily handle different types of requests and responses, whether you’re sending JSON or uploading files.
  • Handy Status Helpers: FetchPHP includes built-in helpers like ok(), isClientError(), isServerError(), and more to simplify handling response statuses.
  • Easy Authentication and Proxies: Need to authenticate or route through a proxy? FetchPHP has you covered.

🚀 Getting Started

FetchPHP is available via Composer, so adding it to your project is super simple. Here’s how to get started:

  1. Install FetchPHP:
composer require yourusername/fetchphp
Enter fullscreen mode Exit fullscreen mode
  1. Make a Request:
<?php

require 'vendor/autoload.php';

use function FetchPHP\fetch;

$response = fetch('https://jsonplaceholder.typicode.com/todos/1');

// Get the JSON response
$data = $response->json();
print_r($data);
Enter fullscreen mode Exit fullscreen mode

In the example above, we’re making a simple GET request and parsing the JSON response. You’ll notice that FetchPHP makes working with HTTP requests in PHP as clean as working with the fetch API in JavaScript.

🛠️ Example Use Cases

Making a POST Request with JSON Data

Need to send data to an API? Here’s how easy it is to use FetchPHP for a POST request:

$response = fetch('https://jsonplaceholder.typicode.com/posts', [
    'method' => 'POST',
    'json' => [
        'title' => 'New Post',
        'body' => 'This is the content of the new post.',
        'userId' => 1,
    ],
]);

echo $response->statusText(); // Should print "Created"
print_r($response->json());
Enter fullscreen mode Exit fullscreen mode

Handling Asynchronous Requests

FetchPHP also supports asynchronous requests using fetchAsync. This is especially useful for performance-critical tasks where you don’t want to block execution:

$promise = fetchAsync('https://jsonplaceholder.typicode.com/todos/1');

$promise->then(function ($response) {
    print_r($response->json());
});

$promise->wait();  // Wait for the request to finish
Enter fullscreen mode Exit fullscreen mode

Multipart Form Data for File Uploads

Uploading files is made easy with FetchPHP’s support for multipart form data:

$response = fetch('https://example.com/upload', [
    'method' => 'POST',
    'multipart' => [
        [
            'name' => 'file',
            'contents' => fopen('/path/to/file.jpg', 'r'),
            'filename' => 'file.jpg'
        ]
    ]
]);

echo $response->statusText();  // Outputs the HTTP status text
Enter fullscreen mode Exit fullscreen mode

🔧 Under the Hood

FetchPHP leverages Guzzle under the hood, one of the most powerful and flexible HTTP clients for PHP. This means you get all the benefits of Guzzle (performance, reliability, rich feature set) with a simpler and more intuitive API inspired by JavaScript’s fetch.

⭐️ Support the Project

I’m really excited to share this project with the PHP community, and I’d love your support! Head over to GitHub, give the project a ⭐️, and share your feedback. Whether it’s bug reports, feature requests, or pull requests, all contributions are welcome! 😊

📢 Conclusion

FetchPHP aims to make HTTP requests in PHP as easy and familiar as JavaScript’s fetch. It’s simple to use, yet powerful enough for any PHP application. I hope it saves you time and effort in your projects. Thanks for checking it out!


🔗 Useful Links

Thanks for reading, and happy coding! 🎉

Top comments (6)

Collapse
 
xwero profile image
david duymelinck • Edited

Fetch is a great api in javascript, because the browsers had different objects to create an ajax request.
The naming could be better. Fetch implies to get something. Most of the times the statuscode is something that gets processed, but not all requests have a payload.

It is good it is an abstraction of guzzle. The problem, in my opinion, is that the functions make guzzle less powerful.
The client is created on each request with fetch. Most of the time when a specific api endpoint is requested, a pre configured client can be used if guzzle is used.
Guzzle has http verb methods. This is easier to read and understand what is going on.

Guzzle is already an abstraction on top of the php methods. Creating an abstraction of an abstraction feels like a cog too many in the machine. This is also the reason I don't use the Laravel http client and other guzzle wrappers.

Collapse
 
thavarshan profile image
Jerome Thayananthajothy

That's a very good point. The function does have the option to use an already existing instance of Guzzle but your point is valid. Need to look into this. Thanks for pointing this out!

Collapse
 
xwero profile image
david duymelinck

I only glanced at the code on github, so I missed the option key client. So you covered that argument.

I think you don't need to change too much, the library is a good package as a helper in the RAD system of thinking. That is also why Laravel has the guzzle wrapper, and many other helper methods.
And when the time comes that is has been decided that the application needs a more futureproof base, the helpers can be unwrapped and the dependencies can be evaluated.

The only other standalone I could find is github.com/WordPress/Requests. So i think space for well crafted request libraries is not saturated.
It will not be my go to library, but I applaud your effort and I hope to see more of your code.

Collapse
 
stevediaz profile image
stevediaz

This looks like a fantastic addition to the PHP ecosystem! 🙌 The FetchPHP library seems to bridge a much-needed gap between PHP and modern HTTP handling, offering a familiar API for those of us coming from JavaScript. The synchronous and asynchronous support is a huge plus, and the inclusion of status helpers will definitely streamline error handling.

Collapse
 
mrpercival profile image
Lawrence Cooke

Just letting you know that the links you have provided are incorrect.

Collapse
 
thavarshan profile image
Jerome Thayananthajothy

Apologies and thanks!