write a function to return someone's ssh key in github in matlab

Here's a function in Matlab to retrieve a user's SSH key from their GitHub account using GitHub API:

main.m
function ssh_key = getGitHubSSHKey(username, token)
% Returns the GitHub SSH key of the given username using GitHub API

% Construct the API url
url = ['https://api.github.com/users/' username '/keys'];

% Set up the http request options
options = weboptions('HeaderFields',{'Authorization',['token ' token]},...
    'ContentType', 'json', 'Timeout', 30);

% Send GET request to GitHub API
response = webread(url, options); 

% Parse the response JSON to extract the SSH key
if ~isempty(response)
    json = jsondecode(response);
    ssh_key = json(1).key;
else 
    ssh_key = '';
end

end
590 chars
23 lines

This function takes in two inputs:

  • username: the Github username of the person whose ssh key we want to retrieve
  • token: a personal access token with read:user scope generated from the Github account settings

The function then constructs the API url to retrieve the SSH keys of the user, sets up options for the http request including header fields and content type, and sends a GET request to the GitHub API.

If the response is successful, the function extracts the first SSH key from the response JSON and returns it as a string. If the response is empty or there are errors in the request, an empty string is returned.

gistlibby LogSnag