Skip to main content

Getting Started with ThorAPI: Your First Steps to API Integration

Welcome to ThorAPI! This guide will walk you through the essential steps to begin using ThorAPI, ensuring a smooth and efficient integration process.

Prerequisites

Before diving into ThorAPI, make sure you have the following prerequisites in place:

  • Valkyr Labs Account: You need an active ThorAPI account. If you don't have one, sign up at ThorAPI Signup to create your account.

  • API Key: Upon signup, you will receive an API key. This key is crucial for authenticating your requests to ThorAPI. Treat it like a password and keep it secure.

  • Basic Understanding of RESTful APIs: Familiarity with RESTful API concepts will be beneficial. If you're new to REST, consider exploring resources like RESTful API Design - REST API Tutorial to get acquainted with the basics.

  • Node.js and npm (for JavaScript SDK): If you plan to use the JavaScript SDK, ensure you have Node.js and npm (Node Package Manager) installed on your system. Download them from Node.js Official Website.

Step 1: Installation

ThorAPI offers a JavaScript SDK to simplify integration with JavaScript-based applications. To install the SDK, use npm:

npm install thorapi-sdk

For other languages, you can directly use HTTP libraries like axios (JavaScript), requests (Python), okhttp (Java), or HttpClient (.NET) to interact with the ThorAPI endpoints.

Step 2: Authentication

Authentication is required for every request to ThorAPI to ensure secure access. You need to include your API key in the Authorization header of your HTTP requests. Here’s how to do it in different environments:

JavaScript (using axios)

const axios = require('axios');

const apiClient = axios.create({
baseURL: 'https://api.thorapi.com', // Replace with ThorAPI base URL
headers: {
'Authorization': `Bearer YOUR_API_KEY` // Replace with your actual API key
}
});

Python (using requests)

import requests

api_key = 'YOUR_API_KEY' # Replace with your actual API key
headers = {
'Authorization': f'Bearer {api_key}'
}

response = requests.get('https://api.thorapi.com/products', headers=headers) # Replace with the desired endpoint
print(response.json())

Java (using okhttp)

import okhttp3.*;

public class ThorAPIClient {
public static void main(String[] args) throws Exception {
OkHttpClient client = new OkHttpClient();
String apiKey = "YOUR_API_KEY"; // Replace with your actual API key

Request request = new Request.Builder()
.url("https://api.thorapi.com/products") // Replace with the desired endpoint
.header("Authorization", "Bearer " + apiKey)
.build();

try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
}
}

ThorAPI generates a fully featured set of backend Java classes featuring Spring Framework features including input validation, SecureField encryption, JPA One-to_Many and Many-to-Many object relationship mapping, and database persistence via JPA.


// the core generated class heirarchy:
+- xxx.xxx.api
<ClassName>Api.java // Used to provide secured (via the Spring Security ACL SecurityContext) persistence services
<ClassName>ApiController.java // the REST controller
<ClassName>ApiDelegate.java // delegate object isolation for DataObjects
<ClassName>Repository.java // Spring JPA repository
<ClassName>PageableRepository.java // Spring JPA pageable repository

+- xxx.xxx.model
<ClassName>.java // Pojo which defines properties, and annotations for ORM, validation, encryption etc.
<ClassName>Service.java // Used to provide secured (via the Spring Security ACL SecurityContext) persistence services

Using the Service classes vs directly accessing the JPA repository

The service classes are annotated with the Spring Security ACL implementations ie:

@PostFilter
public List<XXX> ...

@PreAuthorize
public void setXXX ...

Because of this the classes and methods will only work correctly in a proper SecurityContext container.

If you require lower-level access to the JPA you can easily use the repository classes directly OR use the XXXService.getRepository() method to expose it from the Service class implementation.


@Autowired
PrincipalService principalService; // for secured (Spring Security ACL) Access

@Autowired
PrincipalRepository principalRepository; // for direct JPA Access


...
// you can also mix the usage and utilize the convenience method "getRepository" on all Service classes
List<Principal> principals = principalService.getRepository().findAll();
...

.NET (using HttpClient)

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

public class ThorAPIClient
{
static async Task Main(string[] args)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://api.thorapi.com"); // Replace with ThorAPI base URL
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); // Replace with your actual API key

HttpResponseMessage response = await client.GetAsync("/products"); // Replace with the desired endpoint
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}

Important Security Tip: Never hardcode your API key directly into your application code, especially in client-side code. Use environment variables or secure configuration management systems to store and access your API keys.

Step 3: Making Your First API Request

Let's make a simple GET request to fetch a list of products using the JavaScript SDK (axios):

instance.get('/products')
.then(response => {
console.log(response.data); // Process the product data
})
.catch(error => {
console.error('Error fetching products:', error); // Handle errors appropriately
});

This code snippet sends a GET request to the /products endpoint and logs the response data to the console. Ensure you replace /products with the specific endpoint you wish to access.

Step 4: Explore the API Documentation

To effectively use ThorAPI, explore the comprehensive API documentation. It provides details on all available endpoints, request parameters, response formats, and more. Refer to the ThorAPI Documentation Index for a complete overview of the documentation.

Next Steps

  • Dive Deeper into Endpoints: Explore the API documentation to discover more endpoints and functionalities ThorAPI offers.
  • Implement Error Handling: Enhance your application with robust error handling to gracefully manage API errors and exceptions.
  • Explore SDK Features: If using the JavaScript SDK, explore its additional features and utilities to streamline your API interactions.
  • Contribute to ThorAPI: If you have suggestions or improvements, consider contributing to the ThorAPI project. See our Contributing to ThorAPI guide for more details.

For further reading on API integration and best practices, consider these resources:

Start building amazing applications with ThorAPI today!