Building a Custom Surf Forecast Slider with Surfline API

Jul 5, 2023

Kekai home page
Kekai home page
Kekai home page

I recently had a client who owns a surf hostel in Morocco, and they wanted to display the surf forecast for the nearby surf spots directly on their website. 

As I started researching possible solutions, I came across a WordPress extension called Unofficial Magicseaweed Surf Forecast that was outdated and no longer functioning properly. 

With the lack of a suitable extension, I decided to build my own custom surf forecast slider from scratch. 

This article will guide you through the process of creating a custom surf forecast slider using the Surfline API for WordPress. 

Let’s dive right in!

Creating a Surf Forecast Slider for the Nearby Spot

My client wanted a surf forecast slider that resembled the one provided by Surfline but focused on the surf spot near his hostel.



This slider would enable website visitors to quickly and easily access up-to-date surf forecast information for the nearby location, including details such as wave size, rate, and period.

Surfline does not provide an official API for accessing their surf forecast data.

However, by examining their network requests and understanding the structure of their data, I was able to discover a way to retrieve the necessary surf forecast information.

 In the next sections, I will guide you through the process of building this custom surf forecast slider, utilizing the Surfline API, and implementing it with WordPress.

Let’s get started!

Exploring the Surfline API for Nearby Surf Spots

During my exploration of Surfline’s network requests, I came across a valuable endpoint that provides the information we need for nearby surf spots.

By making a request to the following URL:

https://services.surfline.com/kbyg/spots/nearby?spotId=[ID]

We can retrieve the relevant data for our custom surf forecast slider.

The URL requires one required argument, spotId, which represents the unique identifier of the current surf spot. This allows the API to return the nearby spots based on the location of the chosen spot. Additionally, you have the option to include the units argument to specify the unit of measurement.

By leveraging this Surfline API endpoint, we can fetch the necessary information about the nearby surf spots, such as wave height, rate, and period. This data will be crucial for providing accurate and up-to-date surf forecast information in our custom surf forecast slider.

In the upcoming sections, I will demonstrate how to retrieve and parse the data from this API endpoint and integrate it into our custom surf forecast slider.

Let’s dive in!

Implementing the Backend Code

To retrieve the necessary data from the Surfline API, we will need to implement backend code that handles the API request and response.
Here is an example of the backend code that you can use to fetch the data:

const https = require('https');

exports.surfAPI = async (req, res) => {
  try {
    const options = {
      hostname: 'services.surfline.com',
      path: '/kbyg/spots/nearby?spotId=[ID]&units%5BwaveHeight%5D=M',
      method: 'GET',
      headers: {
        // Headers configuration
      }
    };

    const request = https.request(options, async (response) => {
      let responseData = '';

      response.on('data', (chunk) => {
        responseData += chunk;
      });

      response.on('end', async () => {
        if (response.statusCode === 200) {
          const data = JSON.parse(responseData);

          if (data?.data?.spots) {
            const spotsData = data.data.spots;

            const limitedSpots = spotsData.map(spot => {
              return {
                _id: spot._id,
                name: spot.name,
                waveHeight: {
                  min: spot.waveHeight?.min || 0,
                  max: spot.waveHeight?.max || 0
                },
                ratingKey: spot.rating?.key || '',
                period: spot.swells?.[0]?.period || 0
              };
            });

            res.set('Access-Control-Allow-Origin', '*');
            res.set('Access-Control-Allow-Methods', 'GET');
            res.set('Access-Control-Allow-Headers', 'Content-Type');

            return res.json(limitedSpots);
          } else {
            throw new Error('Invalid API response');
          }
        } else {
          throw new Error('Invalid API response');
        }
      });
    });

    request.on('error', (error) => {
      console.error('Error fetching API data:', error);
      return res.status(500).json({ error: 'Failed to fetch API data' });
    });

    request.end();
  } catch (error) {
    console.error('Error fetching API data:', error);
    return res.status(500).json({ error: 'Failed to fetch API data' });
  }
};

The code is written in JavaScript and is designed to be used as a function for a Google Cloud Function. 

It utilizes the https module to make an HTTP GET request to the Surfline API endpoint. 

The expected response structure for this function is an object with the following properties: _id, name, waveHeight (with min and max sub-properties), ratingKey, and period

This structure aims to provide the necessary surf forecast information for your custom surf forecast slider. 

By incorporating this backend code into your application, you will be able to fetch the surf forecast data from the Surfline API and use it in your custom surf forecast slider.

Integration on WordPress

To integrate the surf forecast slider on WordPress, you’ll need to follow these steps:

  1. Download and install the Code Snippets plugin on your WordPress site.
    This extension allows you to add custom PHP functions without modifying your theme files.

  2. Create a new code snippet and paste the following PHP function:

function display_api_data_shortcode()
{
    // Make the API call using cURL
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, 'YOUR_API_URL');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);

    curl_close($ch);

    // Decode the API response
    $data = json_decode($response);

    // Check if data is an array
    if (isset($data) && is_array($data)) {
        $spots = $data;

        // Prepare the output HTML
        ob_start();
        ?>
        <style>
            /* CSS styles for the surf forecast slider */
            /* ... */
        </style>
        <div class="spot-carousel">
            <?php foreach ($spots as $spot) : ?>
                <div class="spot-item">
                    <a href="https://www.surfline.com/surf-report/<?php echo strtolower(str_replace(' ', '-', $spot->name)); ?>/<?php echo $spot->_id; ?>" target="_blank">
                        <span class="spot-rating-dot conditions<?php echo $spot->ratingKey; ?>"></span>
                        <span><?php echo $spot->name; ?> <strong><?php echo $spot->waveHeight->min; ?>m - <?php echo $spot->waveHeight->max; ?>m </strong><?php echo $spot->period ?>s</span>
                    </a>
                </div>
            <?php endforeach; ?>
        </div>
        <

Save the code snippet, and the function display_api_data_shortcode will be available for use.

To display the surf forecast slider on a page or post, simply add the shortcode [surfline_nearby] in the desired location.

Make sure to publish or update the page or post for the changes to take effect.

Et voilà, you have successfully integrated your custom surf forecast slider on your website!

Kekai home page


If you encounter any challenges or need further assistance while implementing this custom surf forecast slider, please don’t hesitate to reach out to me.

I would be more than happy to help you customize the solution to fit your specific needs.

Frequently asked questions

What is the purpose of the custom surf forecast slider you developed?

The slider allows visitors to access real-time surf forecast data for a nearby surf spot, offering details like wave size, rate, and period.

What URL do you use to fetch surf forecast data from the Surfline API?

The API endpoint is: https://services.surfline.com/kbyg/spots/nearby?spotId=[ID]

How does the surf forecast slider cater to nearby surf spots?

The API request is based on the unique identifier (spotId) of the selected surf spot, ensuring data accuracy for the nearby locations.

How can I incorporate the backend code into my application?

The backend code provided can be integrated into your application, particularly for Google Cloud Functions, to fetch and process surf forecast data.

What benefits does using the backend code offer in surf forecast retrieval?

The backend code streamlines data fetching and structuring from the Surfline API, ensuring efficient and accurate integration.

How can I implement the custom surf forecast slider in WordPress?

Download the Code Snippets plugin, create a new code snippet, add the provided PHP function, and use the [surfline_nearby] shortcode on your desired page or post.

What is the purpose of the custom surf forecast slider you developed?

The slider allows visitors to access real-time surf forecast data for a nearby surf spot, offering details like wave size, rate, and period.

What URL do you use to fetch surf forecast data from the Surfline API?

The API endpoint is: https://services.surfline.com/kbyg/spots/nearby?spotId=[ID]

How does the surf forecast slider cater to nearby surf spots?

The API request is based on the unique identifier (spotId) of the selected surf spot, ensuring data accuracy for the nearby locations.

How can I incorporate the backend code into my application?

The backend code provided can be integrated into your application, particularly for Google Cloud Functions, to fetch and process surf forecast data.

What benefits does using the backend code offer in surf forecast retrieval?

The backend code streamlines data fetching and structuring from the Surfline API, ensuring efficient and accurate integration.

How can I implement the custom surf forecast slider in WordPress?

Download the Code Snippets plugin, create a new code snippet, add the provided PHP function, and use the [surfline_nearby] shortcode on your desired page or post.

Share this article

So, you have a project.
I can take it to the next level.

So, you have a project.
I can take it to the next level.