Current Location: Home> Latest Articles> How to encapsulate date_sunset() as a REST API

How to encapsulate date_sunset() as a REST API

M66 2025-05-30

In this article, we will explore how to encapsulate PHP's date_sunset() function into a REST API. This way, other applications or systems can obtain sunset time via HTTP requests without directly running PHP scripts.

1. What is the date_sunset() function?

PHP's date_sunset() function is used to calculate the sunset time of a specified location. This function returns a Unix timestamp indicating the sunset time of the day. The basic usage is as follows:

 $timestamp = date_sunset(time(), SUNFUNCS_RET_TIMESTAMP, $latitude, $longitude);
echo "Sunset time: " . date("Y-m-d H:i:s", $timestamp);

In the above example, $latitude and $longitude represent the latitude and longitude of the location, and SUNFUNCS_RET_TIMESTAMP represents the return of Unix timestamp format.

2. Why encapsulate date_sunset() into a REST API?

Once date_sunset() is encapsulated into a REST API, you can provide the feature to other applications, allowing them to get sunset time over standard HTTP requests. This approach is suitable for scenarios where you want to access sunset time data without a PHP environment, or integrate the feature into other services.

3. Encapsulate the REST API using PHP and Slim Framework

We will use Slim Framework, a lightweight PHP framework that is especially suitable for building RESTful APIs. First, make sure that the Composer dependency management tool is installed in your development environment and the Slim Framework is installed.

Install Slim Framework

Install the Slim Framework through Composer:

 composer require slim/slim:"4.*"
composer require slim/psr7

Create a REST API

Next, we create a simple PHP script that encapsulates the date_sunset() function into an API.

 <?php

require 'vendor/autoload.php';

use Slim\Factory\AppFactory;

$app = AppFactory::create();

// Define a REST API routing
$app->get('/sunset', function ($request, $response, $args) {
    // Get request parameters
    $latitude = $request->getQueryParams()['latitude'] ?? 0;
    $longitude = $request->getQueryParams()['longitude'] ?? 0;
    
    // Ensure effective latitude and longitude
    if (!is_numeric($latitude) || !is_numeric($longitude)) {
        $response->getBody()->write(json_encode(['error' => 'Invalid latitude or longitude']));
        return $response->withStatus(400)->withHeader('Content-Type', 'application/json');
    }

    // Get the sunset time
    $timestamp = date_sunset(time(), SUNFUNCS_RET_TIMESTAMP, $latitude, $longitude);

    // Format output
    $dateTime = date("Y-m-d H:i:s", $timestamp);
    
    // return JSON response
    $response->getBody()->write(json_encode(['sunset' => $dateTime]));
    return $response->withHeader('Content-Type', 'application/json');
});

// Run the application
$app->run();

In this code snippet, we use Slim Framework to create a simple REST API route /sunset that accepts latitude and longitude as query parameters, calculates and returns sunset time. The result returned is in JSON format, containing the calculated sunset time.

4. Test API

After starting the PHP script, you can test the API via the following URL:

 http://m66.net/sunset?latitude=34.0522&longitude=-118.2437

This will return a JSON response similar to the following:

 {
  "sunset": "2025-04-26 19:42:00"
}

5. Deploy API

If you wish to deploy this API to a production environment, you can choose to host it on any PHP-enabled server, or use cloud services (such as AWS, Heroku, etc.). This API can be run as long as your server supports PHP and HTTP requests.

6. Extend API functionality

You can extend this API as you want. For example, you can add more query parameters such as dates, return data in different formats (such as Unix timestamps or UTC time), or protect the API through an authentication mechanism so that it can only be called by authorized users.