DEV Community

Cover image for Create a Dynamic Website without Backend Using Apisentris
Ardian
Ardian

Posted on

Create a Dynamic Website without Backend Using Apisentris

Have you ever thought about going back to an era where the web was only HTML and CSS + JavaScript?

I have, but always hampered by how to do it if I want to create a dynamic website that must definitely think of backend technology that will be used to handle requests to the server and database. However, at nowadays, a lot of Backend as a Service is emerging which makes it possible to bypass the tired of develop the backend itself.

I developed an application that can act as a Backend as a Service, named Apisentris, backend with API-first approach. I want to prove that Apisentris which I developed can use properly through this tutorial.

Create Apisentris Account

Apisentris is a service that can convert various databases into RESTful API.

Apisentris Landing Page

Apisentris Landing Page

At here, database is called connection. Apisentris provides test connection which can use as a demo so that user can understand immediately about features that provided by Apisentris.

Apisentris - How It Works

Demo connection has provided tables which can be used on that, i.e. programmers table and languages table. After demo connection was saved, a link will appear to the documentation in each table. This documentation page also provides examples of usage with cURL if the user wants to try it directly through Linux / command prompt terminal.

Accessing API from Console

Create index.html

Create file named index.html, see following example:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.1/css/bulma.min.css">
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
  </head>
  <body>
    <section class="section">
      <div class="container">
        <!-- content is going here -->
      </div>
    </section>
  </body>
</html>

This page header only consists of bulma as a css framework to enhance the appearance and also JQuery cdn which is used as a communicator between websites and Apisentris. We will use this index page to display a list of programmers in a table with columns for id, email, first name, last name, and actions. For that, we should replace <!- content is going here -> with this html tag:

<table class="table is-fullwidth" id="records-table">
   <tr>
      <th>ID</th>
      <th>Email</th>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Action</th>
    </tr>
</table>

We will use AJAX to Apisentris account to get programmers. Write tag <script> </ script> before closing </ body> tag as follows:

<script>
    $(document).ready(function() {
        // render list
        $.ajax({
            url: "https://apisentris.com/api/v1/programmers",
            type: "GET",
            beforeSend: function(xhr) {
                xhr.setRequestHeader('client_id', '12000');
                xhr.setRequestHeader('access_token', 'dhxjIWAMYp-aYWpNfVkGPA');
                xhr.setRequestHeader('Content-Type', 'application/json');
            },
            success: function(response) {
                $.each(response, function(i, programmer) {
                      $('<tr id=row-' + programmer.id + '>').append(
                      $('<td>').text(programmer.id),
                      $('<td>').text(programmer.email),
                      $('<td>').text(programmer.firstname),
                      $('<td>').text(programmer.lastname),
                      $('<td data-programmer-id="' + programmer.id + '">').text('')
                    ).appendTo('#records-table').html();
                });
            }
        });
    });
  </script>

The AJAX calls api/v1/programmers endpoint using GET http method. In beforeSend, we should add required headers, i.e. client_id and Apisentris access_token. The response from this endpoint is in the form of an array of json objects. To display in the table that we have previously provided, therefore the response is looped then do append to the table.

Our List of Programmers

index.html - List of Programmers

We just see to the Actions column, that column is still empty. This column should have a menu for Edit and Delete the row in question. For that we can slightly modify our script to accommodate the features we need.

$('*[data-programmer-id='+ programmer.id +']')
    .html('<a href="edit.html?id='+ programmer.id +'">Edit</a>')
    .append('<a class="delete-record" data-programmer-id='+ programmer.id +'> Delete</a>');

Write the script in success callback after each programmer row has been appended to the table.

Because the delete programmer feature doesn't use a new page, then we will add a script to delete it on this index.html page. Removing the programmer is done with AJAX call also towards api/v1/programmers/:id endpoint via DELETE http method.

// assign delete action

$('.delete-record').on('click', function() {
    var programmerId = $(this).attr("data-programmer-id");
    var endpoint     = 'https://apisentris.com/api/v1/programmers/' + programmerId;
// remove from row
    $('#row-' + programmerId).remove();

    // do ajax delete
    $.ajax({
        url: endpoint,
        dataType: 'json',
        type: "DELETE",
        beforeSend: function(xhr) {
            xhr.setRequestHeader('client_id', '12000');
            xhr.setRequestHeader('access_token', 'dhxjIWAMYp-aYWpNfVkGPA');
            xhr.setRequestHeader('Content-Type', 'application/json');
        },
        success: function(response) {
            console.log('Record was successfully deleted.')
        }
    });
});

This is a JavaScript with JQuery from index to display list of programmers also link to go to the edit page and delete the programmer from database.

<script>
    $(document).ready(function() {
        // render list
        $.ajax({
            url: "https://apisentris.com/api/v1/programmers",
            type: "GET",
            beforeSend: function(xhr) {
                xhr.setRequestHeader('client_id', '12000');
                xhr.setRequestHeader('access_token', 'dhxjIWAMYp-aYWpNfVkGPA');
                xhr.setRequestHeader('Content-Type', 'application/json');
            },
            success: function(response) {
                $.each(response, function(i, programmer) {
                      $('<tr id=row-' + programmer.id + '>').append(
                      $('<td>').text(programmer.id),
                      $('<td>').text(programmer.email),
                      $('<td>').text(programmer.firstname),
                      $('<td>').text(programmer.lastname),
                      $('<td data-programmer-id="' + programmer.id + '">').text('')
                    ).appendTo('#records-table').html();
// create link to update
                    $('*[data-programmer-id='+ programmer.id +']')
                      .html('<a href="edit.html?id='+ programmer.id +'">Edit</a>')
                      .append('<a class="delete-record" data-programmer-id='+ programmer.id +'> Delete</a>');
});
// assign delete link
                $('.delete-record').on('click', function() {
                    var programmerId = $(this).attr("data-programmer-id");
                    var endpoint     = 'https://apisentris.com/api/v1/programmers/' + programmerId;
// remove from row
                    $('#row-' + programmerId).remove();

                    // do ajax delete
                    $.ajax({
                        url: endpoint,
                        dataType: 'json',
                        type: "DELETE",
                        beforeSend: function(xhr) {
                            xhr.setRequestHeader('client_id', '12000');
                            xhr.setRequestHeader('access_token', 'dhxjIWAMYp-aYWpNfVkGPA');
                            xhr.setRequestHeader('Content-Type', 'application/json');
                        },
                        success: function(response) {
                            console.log('Record was successfully deleted.')
                        }
                    });
                });
            }
        });
    });
</script>

List of Programmers with Action Links

List of Programmers with Action Links

Create new.html

In this page we will show yoi a form that can be use for do create record function. The HTML and Javascript will be very simple.

<section class="section">
    <div class="container">
      <h1 class="title">
        New Programmer | <a href="index.html">Back</a>
      </h1>
      <div class="field">
        <p class="control has-icons-left has-icons-right">
          <input class="input" type="email" placeholder="Email" name="email">
          <span class="icon is-small is-left">
            <i class="fas fa-envelope"></i>
          </span>
        </p>
      </div>
      <div class="field">
        <p class="control has-icons-left">
          <input class="input" type="text" placeholder="First Name" name="firstname">
          <span class="icon is-small is-left">
            <i class="fas fa-user"></i>
          </span>
        </p>
      </div>
      <div class="field">
        <p class="control has-icons-left">
          <input class="input" type="text" placeholder="Last Name" name="lastname">
        </p>
      </div>
      <div class="field">
        <p class="control">
          <button class="button is-success" id="create-record-btn"> Create
          </button>
        </p>
      </div>
    </div>
  </section>

We will use AJAX call to /api/v1/programmers endpoint with POST http method.

<script>
    $(document).ready(function() {
        $('#create-record-btn').click(function() {
            var email     = $('input[name="email"]').val();
            var firstname = $('input[name="firstname"]').val();
            var lastname  = $('input[name="lastname"]').val();
            var request   = {
                resource: {
                    email: email,
                    firstname: firstname,
                    lastname: lastname
                }
            }

            // do ajax post
            $.ajax({
                url: "https://apisentris.com/api/v1/programmers",
                data: JSON.stringify(request),
                dataType: 'json',
                type: "POST",
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('client_id', '12000');
                    xhr.setRequestHeader('access_token', 'dhxjIWAMYp-aYWpNfVkGPA');
                    xhr.setRequestHeader('Content-Type', 'application/json');
                },
                success: function(response) {
                    window.location.replace('index.html')
                }
            });
        });
    });
  </script>

This page is simple enough, only to take value from the existing form and then send as request body in the form of JSON then in response data can be processed again as needed. For code above after response was succeed then it will be redirected back to the index page.

Create edit.html

The edit page requires us to do AJAX call twice, i.e. to get the data that will be changed which is done with GET http request and when saving that changes with PATCH http method.

GET is done by calling the api/v1/programmers/:id endpoint where :id is the id of the data that has been previously saved and then displays each attribute on each input form.

// get resource details
$.ajax({
    url: endpoint,
    type: "GET",
    beforeSend: function(xhr) {
        xhr.setRequestHeader('client_id', '12000');
        xhr.setRequestHeader('access_token', 'dhxjIWAMYp-aYWpNfVkGPA');
        xhr.setRequestHeader('Content-Type', 'application/json');
    },
    success: function(response) {
        $('input[name="email"]').val(response.email);
        $('input[name="firstname"]').val(response.firstname);
        $('input[name="lastname"]').val(response.lastname);
    }
});

PATCH http method is very similar to the code that we use when performing POST http method, simply changing the AJAX type argument: POST to PATCH

$.ajax({
    url: endpoint,
    data: JSON.stringify(request),
    dataType: 'json',
    type: "PATCH", // uses PATCH http method
    beforeSend: function(xhr) {
        xhr.setRequestHeader('client_id', '12000');
        xhr.setRequestHeader('access_token', 'dhxjIWAMYp-aYWpNfVkGPA');
        xhr.setRequestHeader('Content-Type', 'application/json');
    },
    success: function(response) {
        window.location.replace('index.html')
    }
});

Source Code and Live Demo

Source Code on Github
Live demo

List of Programmers Page

List of Programmers

Programmer Form

New Programmer

Prefilled Programmer Form

Edit Programmer with Prefilled Data

I am @_absyah_ on Twitter and ardian@apisentris.com is my email. Maker of Apisentris. 
Follow Twitter ApisentrisHQ for to knowing latest feature update from Apisentris.

Top comments (4)

Collapse
 
mddanishyusuf profile image
Mohd Danish

Great job. Is this free or premiu? I'm gonna try this to build my APIs with mongodb.

Collapse
 
_absyah_ profile image
Ardian

Thanks.
It is totally free for 1000 requests / month (for sure I will notify you if you nearly reached the limit). You can unlock extra features in premium plans such as larger requests count per month, multiple database connections, user collaboration and custom domain (coming soon). Feel free to ask when you have questions :)

Collapse
 
fajarsiddiq profile image
Fajar Siddiq

This is what i'm looking for!!! i need to learn more of this, this will be the future!

Collapse
 
_absyah_ profile image
Ardian

Thanks. Give it a try.
Just let me know if you need help. I'll be always here :)