How to use Elements


In order to use an Element on your website, you need first to subscribe to its API. Read carefully the provided documentation to see what are the ways to interact with the User Interface, if applicable.

In general, the code to use the Element is very simple and straightforward. The implementation consists of two steps: server-side and client-side.

Server-side

Elements work based on sessions that expire, so your server-side part of the application should call an endpoint providing the pubilc element code and your access key. The result of this method represents a session key that you need to put on client-side.

Important
Never use the Access Key on your client code. This is a common mistake that can lead to serious security issues. Instead, use a method that will fetch the session key on server and return it to client.


Below is an example of ASP.NET Core web API code that gets the session key on the server and return the result to client:


  [ApiController]
  [Route("[controller]")]
  public class ElementSessionsController : ControllerBase
  {
    [HttpGet]
    public IActionResult GetAsync()
    {
        try
        {
            var elementCode = new Guid("... Element Public Code here ...");
            var accessKey = new Guid("... API Access Key here ...");

            return await httpClient.PostAsync("https://elements.apistore.dev/session/{elementCode}/{accessKey}")
        }
        catch
        {
          return {Your exception here}
        }
      }
  }


curl:

      curl --header "Content-Type: application/json" \
        --request POST \
        https://elements.apistore.dev/session/{elementCode}/{accessKey}
  


Client side is very simple and consists of several lines of code:


  <script src="https://js.apistore.dev/v1"></script>

  <script type="module">
    const fetchElementSession = async () =>
    {
      const response = await fetch("https://yoururl/elementsessions");
      const json = await response.json();
      return json;
    }

    const element = new apistore.Element();
    const elementHtml = await element.initialize(fetchElementSession);
    const div = document.getElementById("apistore-element");
    div.appendChild(elementHtml);
  </script>

  <div id="apistore-element"></div>


If you want to test an Element on your website or develop environment, you can use the Countries API, provided by Api Store for free.