Implementing a RESTful API

A RESTful API uses HTTP to send and receive data, so that functionality can be accessed as long as HTTP is available. Through HTTP using GET, POST, PUT and DELETE requests we gain access to CRUD functions.
An HTTP request can be made directly to the API or a wrapper library which provides functions for different use cases.

Using the Stripe API as an example. https://docs.stripe.com/api
The base Stripe API URL is https://api.stripe.com.

A library can be used which already has functions setup to make requests to the API endpoints.
This example will use the PHP library which Stripe provides.

When making requests to the Stripe API you will need a secret key from Stripe to verify your identity.
You can either initialize the library with the secret key.

$stripe = new \Stripe\StripeClient("<secret_key>");
The secret key can also be added to each request. Example request to retrieve a charge with the secret key.

$ch = $stripe->charges->retrieve(
'<charge_id>',
[],
['api_key' => '<secret_key>']
);
$ch->capture();

To make an API request without the PHP library provided by Stripe. You will need to construct the GET request and send it as an HTTP request. Which is what is happening under the hood in the Stripe PHP Library.
This example is in PHP using cURL to send an HTTP GET request.

$url = "https://api.stripe.com/v1/charges/<charge_id>";
$secretKey = "<secret_key>";
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);

// Set the Authorization header with the Bearer token
curl_setopt($ch, CURLOPT_HTTPHEADER, [
  "Authorization: Bearer $secretKey"
]);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);

if (curl_errno($ch)) {
  echo 'cURL error: ' . curl_error($ch);
} else {
  echo 'Response: ' . $response;
}
curl_close($ch);

To make this code more useful you would want to adjust it so that we can make requests to other endpoints other than /charge.

Implementing a RESTful API can be done simply with an HTTP library, a wrapper library can also be used to simplify the process if the library already contains the functions required.

Leave a comment

Your email address will not be published. Required fields are marked *