Skip to main content

Entity Retrieval by ID API

Overview​

The Entity Retrieval API allows authenticated users to fetch detailed information about a specific entity using its unique identifier. This endpoint supports role-based access control and respects entity visibility settings.

Endpoint Details​

  • URL: /api/entities/[id]
  • Method: GET
  • Authentication: Required (JWT Token)
  • Rate Limit: 120 requests per minute for authenticated users
  • Content-Type: application/json

Authentication Requirements​

This endpoint requires authentication. Access to entities depends on:

  • Public entities: Accessible to all authenticated users
  • Member entities: Accessible to MEMBER, CONFIDENTIAL, and ADMIN users
  • Confidential entities: Accessible only to CONFIDENTIAL and ADMIN users

Request Format​

URL Parameters​

  • id (string, required): The unique identifier of the entity

Headers​

GET /api/entities/{entity_id}
Authorization: Bearer <jwt_token>

Example Request​

GET /api/entities/entity_123456789
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Response Format​

Success Response (200 OK)​

{
"id": "entity_123456789",
"name": "TechCorp Solutions",
"description": "Leading software development company specializing in AI and blockchain solutions",
"website": "https://techcorp.example.com",
"email": "contact@techcorp.example.com",
"phone": "+380123456789",
"address": "123 Innovation Street, Kyiv, Ukraine",
"category": "Software Development",
"tags": ["AI", "Blockchain", "Web Development", "Mobile Apps"],
"visibility": "public",
"logo": "https://storage.example.com/logos/techcorp.png",
"socialLinks": {
"linkedin": "https://linkedin.com/company/techcorp",
"twitter": "https://twitter.com/techcorp",
"github": "https://github.com/techcorp"
},
"foundedYear": 2020,
"employeeCount": "11-50",
"industry": "Information Technology",
"location": {
"city": "Kyiv",
"country": "Ukraine",
"coordinates": {
"lat": 50.4501,
"lng": 30.5234
}
},
"onlineStatus": "online",
"lastOnline": "2025-01-14T17:05:00Z",
"createdAt": "2025-01-14T10:00:00Z",
"updatedAt": "2025-01-14T16:30:00Z",
"createdBy": "user_987654321",
"verificationStatus": "verified",
"metrics": {
"viewCount": 1250,
"contactCount": 45,
"opportunityCount": 12
}
}

Error Responses​

401 Unauthorized​

{
"error": "Unauthorized"
}

403 Forbidden​

{
"error": "Access denied"
}

404 Not Found​

{
"error": "Entity not found"
}

500 Internal Server Error​

{
"error": "Internal Server Error"
}

Code Examples​

JavaScript/TypeScript​

async function getEntityById(id: string): Promise<Entity> {
const response = await fetch(`/api/entities/${id}`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`
}
});

if (!response.ok) {
const error = await response.json();
throw new Error(error.error || 'Failed to fetch entity');
}

return response.json();
}

// Usage example
try {
const entity = await getEntityById('entity_123456789');
console.log('Entity details:', entity);
} catch (error) {
console.error('Error fetching entity:', error.message);
}

React Hook Example​

import { useState, useEffect } from 'react';

function useEntity(id: string) {
const [entity, setEntity] = useState<Entity | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);

useEffect(() => {
async function fetchEntity() {
try {
setLoading(true);
setError(null);

const response = await fetch(`/api/entities/${id}`, {
headers: {
'Authorization': `Bearer ${token}`
}
});

if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error);
}

const entityData = await response.json();
setEntity(entityData);
} catch (err) {
setError(err instanceof Error ? err.message : 'Unknown error');
} finally {
setLoading(false);
}
}

if (id) {
fetchEntity();
}
}, [id]);

return { entity, loading, error };
}

// Usage in component
function EntityProfile({ entityId }: { entityId: string }) {
const { entity, loading, error } = useEntity(entityId);

if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error}</div>;
if (!entity) return <div>Entity not found</div>;

return (
<div>
<h1>{entity.name}</h1>
<p>{entity.description}</p>
{/* Render other entity details */}
</div>
);
}

cURL Example​

curl -X GET https://ring.ck.ua/api/entities/entity_123456789 \
-H "Authorization: Bearer YOUR_JWT_TOKEN"

Python Example​

import requests

def get_entity_by_id(entity_id: str, token: str) -> dict:
"""Fetch entity details by ID"""
url = f"https://ring.ck.ua/api/entities/{entity_id}"
headers = {
"Authorization": f"Bearer {token}"
}

response = requests.get(url, headers=headers)

if response.status_code == 200:
return response.json()
elif response.status_code == 404:
raise ValueError("Entity not found")
elif response.status_code == 403:
raise PermissionError("Access denied")
else:
response.raise_for_status()

# Usage
try:
entity = get_entity_by_id("entity_123456789", "your_jwt_token")
print(f"Entity: {entity['name']}")
except Exception as e:
print(f"Error: {e}")

Response Schema​

interface Entity {
id: string; // Unique entity identifier
name: string; // Entity name
description?: string; // Entity description
website?: string; // Official website URL
email?: string; // Contact email
phone?: string; // Contact phone number
address?: string; // Physical address
category: string; // Entity category
tags?: string[]; // Searchable tags
visibility: 'public' | 'member' | 'confidential'; // Visibility level
logo?: string; // Logo URL
socialLinks?: { // Social media links
linkedin?: string;
twitter?: string;
facebook?: string;
github?: string;
};
foundedYear?: number; // Year founded
employeeCount?: string; // Employee count range
industry?: string; // Industry classification
location?: { // Geographic location
city?: string;
country?: string;
coordinates?: {
lat: number;
lng: number;
};
};
onlineStatus: 'online' | 'offline'; // Current online status
lastOnline?: string; // Last online timestamp (ISO 8601)
createdAt: string; // Creation timestamp (ISO 8601)
updatedAt: string; // Last update timestamp (ISO 8601)
createdBy: string; // ID of user who created the entity
verificationStatus?: 'pending' | 'verified' | 'rejected'; // Verification status
metrics?: { // Entity metrics (if available)
viewCount: number;
contactCount: number;
opportunityCount: number;
};
}

Access Control Rules​

Public Entities​

  • Accessible to all authenticated users
  • Full entity details are returned
  • No additional permissions required

Member Entities​

  • Accessible to users with roles: MEMBER, CONFIDENTIAL, ADMIN
  • Visitors and Subscribers receive 403 Forbidden
  • Full entity details are returned to authorized users

Confidential Entities​

  • Accessible only to users with roles: CONFIDENTIAL, ADMIN
  • All other users receive 403 Forbidden
  • May include additional sensitive information

Security Considerations​

  1. Role-Based Access Control: Strict enforcement of visibility rules
  2. Data Sanitization: Sensitive information is filtered based on user role
  3. Audit Logging: All entity access is logged for security monitoring
  4. Rate Limiting: Prevents abuse with 120 requests per minute limit

Performance Considerations​

  1. Caching: Entity data is cached for 5 minutes to improve performance
  2. Database Optimization: Indexed queries for fast entity retrieval
  3. Lazy Loading: Large fields like descriptions are loaded on demand
  4. CDN Integration: Static assets (logos, images) are served via CDN

Testing Examples​

Unit Test Example​

describe('GET /api/entities/[id]', () => {
it('should return entity for valid ID', async () => {
const response = await request(app)
.get('/api/entities/entity_123456789')
.set('Authorization', `Bearer ${validToken}`)
.expect(200);

expect(response.body).toHaveProperty('id', 'entity_123456789');
expect(response.body).toHaveProperty('name');
});

it('should return 404 for non-existent entity', async () => {
const response = await request(app)
.get('/api/entities/non_existent_id')
.set('Authorization', `Bearer ${validToken}`)
.expect(404);

expect(response.body.error).toBe('Entity not found');
});

it('should return 403 for confidential entity without access', async () => {
const response = await request(app)
.get('/api/entities/confidential_entity_id')
.set('Authorization', `Bearer ${memberToken}`)
.expect(403);

expect(response.body.error).toBe('Access denied');
});
});

Changelog​

  • v1.0.0 - Initial implementation with basic entity retrieval
  • v1.1.0 - Added role-based access control
  • v1.2.0 - Enhanced error handling and validation
  • v1.3.0 - Added metrics and verification status
  • v1.4.0 - Improved caching and performance optimization