Our API is a powerful tool to automate certain actions in Ans such as creating question banks, updating exercises and deleting courses. Automating this process is useful for when you want to create, list or update many of these resources, which can save a lot of time. In this article, an example of the requests that can be made using the API is provided. This python script shows how to create, list and update a question bank. It can easily be changed to create, list and update other attributes such as courses or assignments. In this script, you need to set two environment variables: DOMAIN, which should be the URL (https://ans.app/) and TOKEN which is your Bearer Token.
import re from os import environ from requests import get, post, patch class Client(): def __init__(self): self.DOMAIN = environ.get('DOMAIN') self.TOKEN = environ.get('TOKEN') def create_question_bank(self, json): endpoint = f"{self.DOMAIN}/api/v2/question_banks" return self.request('post', endpoint, json=json).json() def list_question_banks(self): endpoint = f"{self.DOMAIN}/api/v2/question_banks" return self.get_all(endpoint) def update_question_bank(self, question_bank_id, json): endpoint = f"{self.DOMAIN}/api/v2/question_banks/{question_bank_id}" return self.request('patch', endpoint, json=json).json() def list_question_bank_exercises(self, question_bank_id): endpoint = f"{self.DOMAIN}/api/v2/question_banks/{question_bank_id}/question_bank_exercises" return self.get_all(endpoint) def update_question_bank_exercise(self, question_bank_exercise_id, json): endpoint = f"{self.DOMAIN}/api/v2/question_bank_exercises/{question_bank_exercise_id}" return self.request('patch', endpoint, json=json).json() def get_all(self, endpoint): records = [] while endpoint: response = self.request('get', endpoint) records.extend(response.json()) if 'rel="next"' not in response.headers['Link']: break if 'rel="prev"' in response.headers['Link']: regex = r' rel="prev",\s<(.*?)>; rel="next"' else: regex = r'rel="first",\s<(.*?)>; rel="next"' match = re.search(regex, response.headers['Link']) endpoint = match.group(1) return records def request(self, method, endpoint, json=None): if method == 'get': response = get(endpoint, headers=self.headers()) elif method == 'post': response = post(endpoint, headers=self.headers(), json=json) elif method == 'patch': response = patch(endpoint, headers=self.headers(), json=json) else: raise ValueError response.raise_for_status() print(response.status_code, method, endpoint, json, '\n') return response def headers(self): return { "Authorization": f"Bearer {self.TOKEN}" }
Comments
0 comments
Please sign in to leave a comment.