Authentication overview
Semantria provides Natural Language Processing (NLP) services through a RESTful API, enabling developers to integrate sentiment analysis, entity extraction, and text categorization into their applications. Access to these services is secured through an authentication mechanism that verifies the identity of the requesting application or user. This process ensures that API requests originate from authorized sources and prevents unauthorized usage of computational resources and data access.
The core of Semantria's authentication model involves API keys, which serve as unique identifiers and secret tokens. When an application makes a request to the Semantria API, these credentials must be included in the request header or body. The Semantria system then validates these credentials against its records. If the credentials are valid and active, the request is processed; otherwise, it is rejected, typically with an HTTP 401 Unauthorized status code. This method is common for web service APIs due to its simplicity and effectiveness in managing access control for programmatic interactions.
Developers interacting with Semantria's API should familiarize themselves with the specific requirements for including their API keys in requests, whether directly via HTTP calls or through one of the provided Semantria SDKs. Adhering to proper credential management and secure coding practices is essential for protecting the integrity and confidentiality of data processed by Semantria, as well as preventing unauthorized charges or service disruptions.
Supported authentication methods
Semantria primarily supports API key-based authentication for its API. This method involves using a pair of credentials: a Consumer Key (often referred to as the API Key) and a Consumer Secret. These credentials are generated for each user account and are used to sign or authorize requests to the Semantria API. While the underlying mechanism for validating these keys is proprietary, the interaction model for developers is straightforward.
The API key approach is widely adopted for its balance of security and ease of implementation, particularly for server-to-server communication where a user's direct interaction is not required for each API call. It allows for granular control over API access, as keys can be revoked or regenerated if compromised. Semantria's documentation provides specific guidance on how to pass these keys within different programming environments, ensuring compatibility across various application architectures.
All communication with the Semantria API is expected to occur over HTTPS (Hypertext Transfer Protocol Secure), which provides encryption in transit. This ensures that the API keys and any data exchanged, such as text submitted for analysis or results received, are protected from eavesdropping and tampering during transmission across the network. The use of TLS (Transport Layer Security) is a standard practice for securing web API communications, as detailed by organizations like the Internet Engineering Task Force in TLS 1.3 specifications.
Authentication Methods Table
| Method | Description | When to Use | Security Level |
|---|---|---|---|
| API Key (Consumer Key & Secret) | A pair of unique string credentials used to identify and authenticate an application. The Consumer Key identifies the application, and the Consumer Secret is used to sign requests. | Primarily for server-side applications, backend services, and scripts that interact directly with the Semantria API. Suitable for most common integration patterns. | High (when securely stored and transmitted over HTTPS). Relies on the secrecy of the Consumer Secret. |
Getting your credentials
To begin using the Semantria API, you must first obtain your unique API credentials. These credentials consist of a Consumer Key and a Consumer Secret, which are essential for authenticating your requests. The process typically involves registering for a Semantria account and navigating to the developer or API section of your dashboard.
- Sign Up or Log In: If you don't already have an account, you'll need to sign up for a Semantria plan. A free Developer Plan offering 5,000 API calls is available for testing and development purposes. Existing users can simply log into their Semantria account.
- Access Developer Dashboard: Once logged in, navigate to the developer dashboard or API settings section. The exact path may vary but is usually labeled something like "API Keys," "Developer Settings," or "My Applications" within the account management area.
- Generate/Retrieve Keys: Within this section, you will find your Consumer Key and Consumer Secret. If you are setting up for the first time, you might need to generate a new key pair. Semantria typically provides a clear interface for this. It's crucial to note down or copy these credentials immediately, especially the Consumer Secret, as it often cannot be retrieved again after initial generation for security reasons. If lost, it may require generating a new secret.
- Store Securely: After obtaining your credentials, store them in a secure location. Avoid hardcoding them directly into your application's source code, especially for client-side applications or publicly accessible repositories. Environment variables, secure configuration files, or dedicated secret management services are preferred methods.
Semantria's API documentation provides detailed instructions specific to their platform for credential retrieval and management, which should be consulted for the most up-to-date information.
Authenticated request example
Authenticating requests to the Semantria API involves including your Consumer Key and Consumer Secret. While the exact method can vary slightly depending on the SDK or programming language, the fundamental principle remains the same: the credentials must be part of the request. Here, we'll illustrate a basic example using Python, one of Semantria's primary language examples, making a request to the Semantria API for sentiment analysis.
First, ensure you have your CONSUMER_KEY and CONSUMER_SECRET readily available from your Semantria developer account. For this example, we'll assume you're using the Semantria Python SDK. If you haven't installed it, you can do so via pip:
pip install semantria
Now, here's a Python code snippet demonstrating an authenticated request:
import semantria
import json
import time
# Replace with your actual Consumer Key and Consumer Secret
CONSUMER_KEY = "YOUR_SEMANTRIAL_CONSUMER_KEY"
CONSUMER_SECRET = "YOUR_SEMANTRIAL_CONSUMER_SECRET"
# Initialize Semantria session
session = semantria.Session(CONSUMER_KEY, CONSUMER_SECRET, verify_ssl=True)
# Define the text to be analyzed
document_text = "Semantria's API is incredibly powerful and easy to integrate for text analytics."
# Create a document object for the API call
doc = {"id": "test_doc_1", "text": document_text}
# Queue the document for processing
# The queueDocument method sends the document to Semantria for analysis
# It returns a list of successfully queued documents.
queued_docs = session.queueDocument(doc)
if queued_docs:
print(f"Document 'test_doc_1' successfully queued for analysis.")
print("Waiting for processing to complete...")
# Polling for results (Semantria processing is asynchronous)
# In a real application, you might use webhooks or a more sophisticated polling strategy.
for _ in range(10): # Try up to 10 times
time.sleep(2) # Wait 2 seconds before polling again
results = session.getProcessedDocuments()
if results:
print("\nAnalysis Results:")
for result in results:
if result["id"] == "test_doc_1":
print(f"Document ID: {result['id']}")
print(f"Sentiment Score: {result['sentiment_score']}")
print(f"Sentiment Polarity: {result['sentiment_polarity']}")
print(f"Entities: {', '.join([e['title'] for e in result.get('entities', [])])}")
print(f"Themes: {', '.join([t['title'] for t in result.get('themes', [])])}")
break
break
else:
print("Document processing timed out or no results retrieved.")
else:
print("Failed to queue document.")
In this example:
- The
semantria.Sessionobject is initialized with yourCONSUMER_KEYandCONSUMER_SECRET. This session object then handles the secure transmission of these credentials with every subsequent API call. - The
verify_ssl=Trueparameter ensures that SSL certificate validation is performed, which is critical for secure HTTPS communication, preventing man-in-the-middle attacks. - Documents are queued for processing asynchronously, a common pattern for NLP services that require time to analyze large texts. The example includes a basic polling mechanism to retrieve results once processing is complete.
- The output will include details like sentiment score, polarity, and extracted entities/themes, demonstrating successful authentication and data processing.
For other languages, similar SDKs or direct HTTP request libraries (e.g., cURL) can be used, with the API keys typically passed in HTTP headers (e.g., Authorization header) or as part of the request payload, depending on the specific API endpoint and version. Always refer to the Semantria API 2.0 reference for precise endpoint and parameter details.
Security best practices
Securing your Semantria API integration is crucial to prevent unauthorized access, protect sensitive data, and maintain the integrity of your applications. Adhering to established security best practices for API keys is essential.
- Never Expose API Keys in Client-Side Code: Your Consumer Key and Consumer Secret should never be embedded directly into client-side code (e.g., JavaScript in a web browser, mobile app frontends). This would expose them to end-users, potentially allowing malicious actors to steal and misuse your credentials. All API calls involving your secret key should originate from your secure backend servers.
- Use Environment Variables or Secret Management Services: Store your API keys in environment variables, dedicated configuration files that are not committed to version control, or specialized secret management services (e.g., AWS Secrets Manager, Google Secret Manager, Azure Key Vault). This separates credentials from your codebase and makes them easier to manage and rotate. For example, Google's authentication documentation provides general guidance on securing API keys.
- Restrict API Key Privileges: While Semantria's API keys typically grant full access to your account's processing capabilities, if future versions or related services offer more granular permissions, always follow the principle of least privilege. Grant only the necessary permissions required for your application to function.
- Regularly Rotate API Keys: Periodically rotate your API keys, ideally every 90 days or less. This minimizes the window of opportunity for a compromised key to be exploited. If you suspect a key has been compromised, revoke it immediately and generate a new one.
- Monitor API Usage: Keep a close eye on your Semantria API usage metrics. Unusual spikes in activity or requests from unexpected geographical locations could indicate unauthorized use of your keys. Semantria's dashboard or billing information may provide these insights.
- Implement HTTPS/TLS: Always ensure that all communication with the Semantria API occurs over HTTPS. The Semantria SDKs typically handle this by default, but if you are making raw HTTP requests, explicitly enforce TLS 1.2 or higher to encrypt data in transit and protect your API keys from interception.
- Validate and Sanitize Inputs: Although not directly an authentication concern, validating and sanitizing all input data sent to the Semantria API is a critical security practice. This prevents injection attacks and ensures that only expected and safe data is processed.
- Error Handling and Logging: Implement robust error handling for API authentication failures. Log these failures for auditing and security monitoring, but be careful not to log the actual API keys themselves. Generic messages like "Authentication failed" are preferable in public-facing logs.
By consistently applying these security measures, developers can significantly reduce the risk of security vulnerabilities in their applications that integrate with the Semantria API, safeguarding data and maintaining operational integrity.