from typing import List, Optional, Dict
from dataclasses import dataclass
from datetime import datetime
import requests
@dataclass
class DeadlinePeriod:
measure: str # "hours", "days", "weeks", "months"
value: int
@dataclass
class Course:
id: int
name: str
annotation: str
is_draft: bool
created_at: datetime
updated_at: datetime
published_at: datetime
@dataclass
class Assignment:
assigned_at: datetime
deadline_at: Optional[datetime]
deadline_period: Optional[DeadlinePeriod]
course: Course
def get_group_assignments(api_key: str, group_id: int) -> List[Assignment]:
"""
Fetch all assignments for a specific group.
Args:
api_key: Your API key
group_id: The ID of the group to fetch assignments for
Returns:
List of Assignment objects containing course and deadline information
Raises:
ValueError: If the group is not found
requests.exceptions.RequestException: For API communication errors
"""
url = f"https://YOURSITE.konstant.ly/openapi/v1/groups/{group_id}/assignments"
headers = {"X-API-KEY": api_key}
try:
response = requests.get(url, headers=headers)
if response.status_code == 404:
raise ValueError(f"Group {group_id} not found")
response.raise_for_status()
data = response.json()
assignments = []
for item in data["assignments"]:
# Parse deadline information
deadline_at = None
if "deadlineAt" in item:
deadline_at = datetime.fromtimestamp(item["deadlineAt"])
deadline_period = None
if "deadlinePeriod" in item:
deadline_period = DeadlinePeriod(
measure=item["deadlinePeriod"]["measure"],
value=item["deadlinePeriod"]["value"]
)
# Parse course information
course = Course(
id=item["course"]["id"],
name=item["course"]["name"],
annotation=item["course"]["annotation"],
is_draft=item["course"]["isDraft"],
created_at=datetime.fromtimestamp(item["course"]["createdAt"]),
updated_at=datetime.fromtimestamp(item["course"]["updatedAt"]),
published_at=datetime.fromtimestamp(item["course"]["publishedAt"])
)
assignment = Assignment(
assigned_at=datetime.fromtimestamp(item["assignedAt"]),
deadline_at=deadline_at,
deadline_period=deadline_period,
course=course
)
assignments.append(assignment)
return assignments
except requests.exceptions.RequestException as e:
print(f"Error fetching assignments: {str(e)}")
if hasattr(e, "response") and e.response is not None:
print(f"Response: {e.response.text}")
raise
if __name__ == "__main__":
try:
assignments = get_group_assignments("YOUR_API_KEY", 123)
print(f"Found {len(assignments)} assignments\n")
for assignment in assignments:
print(f"Course: {assignment.course.name}")
print(f"Status: {'Draft' if assignment.course.is_draft else 'Published'}")
print(f"Assigned: {assignment.assigned_at.strftime('%Y-%m-%d %H:%M:%S')}")
if assignment.deadline_at:
print(f"Deadline: {assignment.deadline_at.strftime('%Y-%m-%d %H:%M:%S')}")
elif assignment.deadline_period:
print(f"Deadline: {assignment.deadline_period.value} {assignment.deadline_period.measure}")
print(f"Description: {assignment.course.annotation}")
print()
except ValueError as e:
print(f"Error: {str(e)}")
except Exception as e:
print(f"Failed to get assignments: {str(e)}")
{
"assignments": [
{
"assignedAt": 1443183322,
"deadlineAt": 1444188932,
"course": {
"id": 123,
"name": "Sales Strategy Fundamentals",
"annotation": "Learn essential sales strategies and techniques",
"isDraft": false,
"createdAt": 1507807711,
"updatedAt": 1507808372,
"publishedAt": 1508225229
}
},
{
"assignedAt": 1443183400,
"deadlinePeriod": {
"measure": "months",
"value": 2
},
"course": {
"id": 124,
"name": "Customer Relationship Management",
"annotation": "Master modern CRM principles and practices",
"isDraft": false,
"createdAt": 1507807800,
"updatedAt": 1507808400,
"publishedAt": 1508225300
}
}
],
"totalCount": 2
}
Get a list of the courses assigned to the group
from typing import List, Optional, Dict
from dataclasses import dataclass
from datetime import datetime
import requests
@dataclass
class DeadlinePeriod:
measure: str # "hours", "days", "weeks", "months"
value: int
@dataclass
class Course:
id: int
name: str
annotation: str
is_draft: bool
created_at: datetime
updated_at: datetime
published_at: datetime
@dataclass
class Assignment:
assigned_at: datetime
deadline_at: Optional[datetime]
deadline_period: Optional[DeadlinePeriod]
course: Course
def get_group_assignments(api_key: str, group_id: int) -> List[Assignment]:
"""
Fetch all assignments for a specific group.
Args:
api_key: Your API key
group_id: The ID of the group to fetch assignments for
Returns:
List of Assignment objects containing course and deadline information
Raises:
ValueError: If the group is not found
requests.exceptions.RequestException: For API communication errors
"""
url = f"https://YOURSITE.konstant.ly/openapi/v1/groups/{group_id}/assignments"
headers = {"X-API-KEY": api_key}
try:
response = requests.get(url, headers=headers)
if response.status_code == 404:
raise ValueError(f"Group {group_id} not found")
response.raise_for_status()
data = response.json()
assignments = []
for item in data["assignments"]:
# Parse deadline information
deadline_at = None
if "deadlineAt" in item:
deadline_at = datetime.fromtimestamp(item["deadlineAt"])
deadline_period = None
if "deadlinePeriod" in item:
deadline_period = DeadlinePeriod(
measure=item["deadlinePeriod"]["measure"],
value=item["deadlinePeriod"]["value"]
)
# Parse course information
course = Course(
id=item["course"]["id"],
name=item["course"]["name"],
annotation=item["course"]["annotation"],
is_draft=item["course"]["isDraft"],
created_at=datetime.fromtimestamp(item["course"]["createdAt"]),
updated_at=datetime.fromtimestamp(item["course"]["updatedAt"]),
published_at=datetime.fromtimestamp(item["course"]["publishedAt"])
)
assignment = Assignment(
assigned_at=datetime.fromtimestamp(item["assignedAt"]),
deadline_at=deadline_at,
deadline_period=deadline_period,
course=course
)
assignments.append(assignment)
return assignments
except requests.exceptions.RequestException as e:
print(f"Error fetching assignments: {str(e)}")
if hasattr(e, "response") and e.response is not None:
print(f"Response: {e.response.text}")
raise
if __name__ == "__main__":
try:
assignments = get_group_assignments("YOUR_API_KEY", 123)
print(f"Found {len(assignments)} assignments\n")
for assignment in assignments:
print(f"Course: {assignment.course.name}")
print(f"Status: {'Draft' if assignment.course.is_draft else 'Published'}")
print(f"Assigned: {assignment.assigned_at.strftime('%Y-%m-%d %H:%M:%S')}")
if assignment.deadline_at:
print(f"Deadline: {assignment.deadline_at.strftime('%Y-%m-%d %H:%M:%S')}")
elif assignment.deadline_period:
print(f"Deadline: {assignment.deadline_period.value} {assignment.deadline_period.measure}")
print(f"Description: {assignment.course.annotation}")
print()
except ValueError as e:
print(f"Error: {str(e)}")
except Exception as e:
print(f"Failed to get assignments: {str(e)}")
{
"assignments": [
{
"assignedAt": 1443183322,
"deadlineAt": 1444188932,
"course": {
"id": 123,
"name": "Sales Strategy Fundamentals",
"annotation": "Learn essential sales strategies and techniques",
"isDraft": false,
"createdAt": 1507807711,
"updatedAt": 1507808372,
"publishedAt": 1508225229
}
},
{
"assignedAt": 1443183400,
"deadlinePeriod": {
"measure": "months",
"value": 2
},
"course": {
"id": 124,
"name": "Customer Relationship Management",
"annotation": "Master modern CRM principles and practices",
"isDraft": false,
"createdAt": 1507807800,
"updatedAt": 1507808400,
"publishedAt": 1508225300
}
}
],
"totalCount": 2
}
Show Assignment object properties
Show Course properties
from typing import List, Optional, Dict
from dataclasses import dataclass
from datetime import datetime
import requests
@dataclass
class DeadlinePeriod:
measure: str # "hours", "days", "weeks", "months"
value: int
@dataclass
class Course:
id: int
name: str
annotation: str
is_draft: bool
created_at: datetime
updated_at: datetime
published_at: datetime
@dataclass
class Assignment:
assigned_at: datetime
deadline_at: Optional[datetime]
deadline_period: Optional[DeadlinePeriod]
course: Course
def get_group_assignments(api_key: str, group_id: int) -> List[Assignment]:
"""
Fetch all assignments for a specific group.
Args:
api_key: Your API key
group_id: The ID of the group to fetch assignments for
Returns:
List of Assignment objects containing course and deadline information
Raises:
ValueError: If the group is not found
requests.exceptions.RequestException: For API communication errors
"""
url = f"https://YOURSITE.konstant.ly/openapi/v1/groups/{group_id}/assignments"
headers = {"X-API-KEY": api_key}
try:
response = requests.get(url, headers=headers)
if response.status_code == 404:
raise ValueError(f"Group {group_id} not found")
response.raise_for_status()
data = response.json()
assignments = []
for item in data["assignments"]:
# Parse deadline information
deadline_at = None
if "deadlineAt" in item:
deadline_at = datetime.fromtimestamp(item["deadlineAt"])
deadline_period = None
if "deadlinePeriod" in item:
deadline_period = DeadlinePeriod(
measure=item["deadlinePeriod"]["measure"],
value=item["deadlinePeriod"]["value"]
)
# Parse course information
course = Course(
id=item["course"]["id"],
name=item["course"]["name"],
annotation=item["course"]["annotation"],
is_draft=item["course"]["isDraft"],
created_at=datetime.fromtimestamp(item["course"]["createdAt"]),
updated_at=datetime.fromtimestamp(item["course"]["updatedAt"]),
published_at=datetime.fromtimestamp(item["course"]["publishedAt"])
)
assignment = Assignment(
assigned_at=datetime.fromtimestamp(item["assignedAt"]),
deadline_at=deadline_at,
deadline_period=deadline_period,
course=course
)
assignments.append(assignment)
return assignments
except requests.exceptions.RequestException as e:
print(f"Error fetching assignments: {str(e)}")
if hasattr(e, "response") and e.response is not None:
print(f"Response: {e.response.text}")
raise
if __name__ == "__main__":
try:
assignments = get_group_assignments("YOUR_API_KEY", 123)
print(f"Found {len(assignments)} assignments\n")
for assignment in assignments:
print(f"Course: {assignment.course.name}")
print(f"Status: {'Draft' if assignment.course.is_draft else 'Published'}")
print(f"Assigned: {assignment.assigned_at.strftime('%Y-%m-%d %H:%M:%S')}")
if assignment.deadline_at:
print(f"Deadline: {assignment.deadline_at.strftime('%Y-%m-%d %H:%M:%S')}")
elif assignment.deadline_period:
print(f"Deadline: {assignment.deadline_period.value} {assignment.deadline_period.measure}")
print(f"Description: {assignment.course.annotation}")
print()
except ValueError as e:
print(f"Error: {str(e)}")
except Exception as e:
print(f"Failed to get assignments: {str(e)}")
{
"assignments": [
{
"assignedAt": 1443183322,
"deadlineAt": 1444188932,
"course": {
"id": 123,
"name": "Sales Strategy Fundamentals",
"annotation": "Learn essential sales strategies and techniques",
"isDraft": false,
"createdAt": 1507807711,
"updatedAt": 1507808372,
"publishedAt": 1508225229
}
},
{
"assignedAt": 1443183400,
"deadlinePeriod": {
"measure": "months",
"value": 2
},
"course": {
"id": 124,
"name": "Customer Relationship Management",
"annotation": "Master modern CRM principles and practices",
"isDraft": false,
"createdAt": 1507807800,
"updatedAt": 1507808400,
"publishedAt": 1508225300
}
}
],
"totalCount": 2
}
Was this page helpful?