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β
- Role-Based Access Control: Strict enforcement of visibility rules
- Data Sanitization: Sensitive information is filtered based on user role
- Audit Logging: All entity access is logged for security monitoring
- Rate Limiting: Prevents abuse with 120 requests per minute limit
Performance Considerationsβ
- Caching: Entity data is cached for 5 minutes to improve performance
- Database Optimization: Indexed queries for fast entity retrieval
- Lazy Loading: Large fields like descriptions are loaded on demand
- 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');
});
});
Related Endpointsβ
- Create Entity - Create new entity
- Update Entity - Modify existing entity
- Delete Entity - Remove entity
- List Entities - Browse all entities
- List Entities - Browse and search entities
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