Creating APIs

Creating new APIs on Celestial is an easy three step process!

1

Create the HTML form or button

2

Create API endpoint

3

Create the javascript function

Form Walkthrough

You can build your form using a built-in form generator. This streamlines your forms and makes sure that the APIs are consistent.

{{ startForm("/api/test/", "post", "testAPIExample") }}
    {{ submitFormButton("Test the API", "btn btn-outline-secondary") }}
{{ endForm() }}

Turns into:


	<form data-api-form="" action="/api/test/" method="post" data-callback="testAPIExample" enctype="multipart/form-data">
		<button type="submit" class="btn btn-outline-secondary" data-text="Test the API">Test the API</button>
	</form>

Breaking down the form line by line

{{ startForm("/api/test/", "post", "testAPIExample") }}

The first parameter is the API URL endpoint. You will set this up in your backend after this step.

The second parameter is what type of HTTP method you want to use. Its pretty easy to just use POST for these.

The third parameter is your javascript callback function. Once this form is completed, Celestial will look for a function with that name, and run it for you. You will set this up in part 3 of the API example.

{{ submitFormButton("Test the API", "btn btn-outline-secondary") }}

The first parameter is the text that you want to show up on the button. This supports HTML so you can add in icons or images here.

The second parameter is the list of classes you'd like to apply to the button.

{{ endForm() }}

No parameters on this one. This just adds a closing </form> tag. Useful for keeping your IDE or code editor's code sniffing valid.

Form Example

{{ startForm("/api/test/", "post", "testAPIExample") }}

		
	<h1>Contact Us</h1>
	<input type="text" class="form-control mb-3" name="name" placeholder="Enter your name">

		{{ submitFormButton("Test the API", "btn btn-outline-secondary") }}
{{ endForm() }}

That's all you need to get started!

Button Example

Sometimes you need a button to do an action like deleting a user, marking a notification as 'read', or adding a friend to your account. You can do this in a similar manner to the form example by using a built-in function.

This one has a few more options than the form so we'll break them down individually.

{{  APIButton('/api/test/', 'post', 'Test API', 'testAPIExample', 'btn btn-secondary') }}
  • The first parameter is the API URL endpoint. You will set this up in your backend after this step.
  • The second parameter is what type of HTTP method you want to use. Its pretty easy to just use POST for these.
  • The third parameter is the text that you want to show up on the button. This supports HTML so you can add in icons or images here.
  • The fourth parameter is your javascript callback function. Once this form is completed, Celestial will look for a function with that name, and run it for you. You will set this up in part 3 of the API example.
  • The fifth parameter is the list of classes you'd like to apply to the button.

The button example is essentially the Form and the Submit Button combined into one.

When you call the above function, it will ouput:


	<button class="btn btn-secondary"
					type="button"
					data-api-btn
					data-action="/api/test/"
					data-method="post"
					data-text="Test API"
					data-callback="testAPIExample"
					data-processing="false">Test API</button>

API Endpoint Template

Navigate to project-files/site-apis.php. Inside, you will find a similar setup to the site-routes.php file.

APIs can be called using POST, PUT, PATCH, and DELETE. To keep things simple, you could just use POST method. You can read more about HTTP Methods on the Mozilla Developer Network.

// Your API name goes here and a description if you want.
$Router->post('/api/api-url-here/', function () {
    // Set your globals first

    // Set response defaults in case of failure.

    // Set your validations if you have any

    // API Actions on the validated data

    // If all previous actions were successful, build the response array

    // Complete the API

});

Example API

We want this API to fire on POST requests. We'll go line by line and show what its doing.

// Test API
$Router->post('/api/test/', function () {
    // Set your globals first
    global $Create;

    // Set response defaults in case of failure.
    $response = [];
    $response['status'] = false;
    $response['message'] = 'unable to complete request';

    // Set your validations if you have any
    // This API requires the form value 'name'. If it doesnt exist, the api will exit.
    $name = $_POST['name'] ?? $Create->JSON($response);

    // API Actions on the validated data
    // Construct a message
    $message = "Thank you for contacting us, " . $name;

    // If all previous actions were successful, build the response array
    $response['status'] = true;
    $response['message'] = $message;

    // Complete the API
    $Create->JSON($response);
});

Calling Global Variables

global $Create;

$Create is one of a few built in functions that you can use on the site. In this case, we are looking for the method called 'JSON'. This method takes an array (the $response array that you will build), and automatically sets your correct headers and exits the API with the JSON data. We'll show that in more detail below.

Create the default response

// Set response defaults in case of failure.
$response = [];
$response['status'] = false;
$response['message'] = 'unable to complete request';

This is useful if you require form values and the user misses one, or a malicious user isn't properly using the form. It will exit with two values: status, and message. You can use these in your javascript to perform actions such as highlighting missing form fields, or creating custom messaging for the user to see.

This is also helpful for debugging your APIs because you can set a $response['message'] for every validation you perform, and will be able to see which steps your API is breaking at.

If you dont need to process form data, you can omit this.

Requiring form values

// This API requires the form value 'name'. If it doesnt exist, the api will exit.
$name = $_POST['name'] ?? $Create->JSON($response);

Here, you can set the required form values for the API. In this example, it's looking for the 'name' value. If it doesnt exist, it will exit the API with the message you set above. It is using the PHP 7 'Null Coalescing Operator', which is an awesome and easy replacement to the isset() function.

// Old way
if(isset($_POST['name'])) {
    $name = $_POST['name'];
} else {
    $Create->JSON($response);
}

// New way
$name = $_POST['name'] ?? $Create->JSON($response);

You could also set it to return a default response by changing out the last part for a string (or anything).

$name = $_POST['name'] ?? 'Super Developer';

If you need the additional flexibility using the traditional isset() method, feel free to use it.

The main API actions

// Construct a message
$message = 'Thank you for contacting us, ' . $name;

This API example constructs a message saying "Thank you for contacting us, $name". Pretty simple. This area is where you would define all the actions that you could take. If you needed to update content in the database, those actions would be performed here.

Building the API response

// If all previous actions were successful, build the response array
$response['status'] = true;
$response['message'] = $message;

If all of your API actions (this example just has one) are successful, then build the final response to send to the user. This includes setting the $response['status'] to true. You can also update the $response['message'] for your javascript to read. This example just returns the user's name.

Completing the API

// Complete the API
$Create->JSON($response);

With all the above completed, send the $response value in JSON format back to the client. Done!

Testing with Postman

Example of Postman hitting the test API we built.

You can test your new API by creating a new POST request on Postman. If you aren't familiar with Postman, it is a great, free, tool to test APIs. It can work with any website and has tons of options to customize your requests.

  1. Set the URL to point to your API URL
  2. Set the Body to be "form-data"
  3. Set your required parameters (in this case, 'name')
  4. Hit Send!

If you aren't able to install Postman, you can use Postwoman, the online version of Postman.

Javascript Callback

Whenever you make an API request, you can let the user know with a javascript callback. When we wrote our form at the top, we added in "testAPIExample" as the javascript function. We can define that now!

Navigate to public/js/api-functions.js. In here, you can define all of your callback functions.

function testAPIExample(response, el, text) {
    if(response['status']) {
        el.innerText = "✔";
        alert("Success!");

    } else {
        el.innerText = "✖";
        alert("The input field for 'name' is missing!");
    }
}

When you define an API function, you get access to three things:

  • response: This is the JSON data sent from your API. You can use it to do conditional statements like the one above, showing a checkmark for success, and an X for a failure.
  • el: This is the button element that was interacted with. You can use this to show the user that an event is happening, has happened, or will happen. You can also ignore this and create your own notification system.
  • text: This is the original text of the button. This is useful if you are using the button to notify the user that an action has occurred. You can ignore this if you want and the button will return back to the previous text.

Inside the function, you can do anything you want. Show a notification bar, animate a row on a table to disappear or to add, show sparkles across the page, and even change the user's site theme.