'Connect Android App to Github API
I've been checking around for some time, but still can't find information on this how exactly to connect my android app to the Github API. I had it registered, had a token as well, read about the endpoints and everything, but cannot understand where the token to be used. May somebody give me a hint?
Solution 1:[1]
I've used below code to connect to GitHub Search Repo API in my android app.
//Method 1: To Authorize API access for all HTTP call
//Uncomment this part of code and input your username and password
// Authenticator.setDefault(new Authenticator() {
// @Override
// protected PasswordAuthentication getPasswordAuthentication() {
// return new PasswordAuthentication("username", "password".toCharArray());
// }
// });
HttpURLConnection urlConnection;
URL url;
InputStream inputStream;
try{
url = new URL("https://api.github.com/search/repositories?q="+"searchText");
urlConnection = (HttpURLConnection) url.openConnection();
//Method 2: To Authorize API access while making HTTP request
//Uncomment this part of code and input your username and password
// String basicAuth = "Basic "+Base64.encodeToString("username:password".getBytes(), Base64.NO_WRAP);
// urlConnection.setRequestProperty ("Authorization", basicAuth);
//set request type
urlConnection.setRequestMethod("GET");
//if you uncomment the following line GitHub API will not respond
// urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
//check for HTTP response
int httpStatus = urlConnection.getResponseCode();
//if HTTP response is 200 i.e. HTTP_OK read inputstream else read errorstream
if (httpStatus != HttpURLConnection.HTTP_OK) {
inputStream = urlConnection.getErrorStream();
//print GitHub api hearder data
Map<String, List<String>> map = urlConnection.getHeaderFields();
System.out.println("Printing Response Header...\n");
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
System.out.println(entry.getKey()
+ " : " + entry.getValue());
}
}
else {
inputStream = urlConnection.getInputStream();
}
//read inputstream
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String temp,response="";
while((temp = bufferedReader.readLine())!=null){
response+=temp;
}
//GitHub api has limit to access over http.
//Api rate limit is 10req/min for unauthenticated user and 30req/min is for authenticated user
boolean apiLimitExceeded = "false";
if(response.contains("API rate limit exceeded")){
apiLimitExceeded =true;
}else {
//convert data string into JSONObject
JSONObject obj = (JSONObject) new JSONTokener(response).nextValue();
JSONArray items = obj.getJSONArray("items");
//total result count and result status
total_count = obj.getString("total_count");
incomplete_results = obj.getString("incomplete_results");
}
urlConnection.disconnect();
} catch (MalformedURLException | ProtocolException | JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Check out my GitHub project to get a complete idea on how to use GitHub search repo API in Android App. Link: https://github.com/kvipul/Search-GitHub-Repo
There are many filters that GitHub API provides. Check out the Documentation of GitHub search API for more details -https://developer.github.com/v3/search/
Solution 2:[2]
The full command would be like:
@bot.command()
async def banner(ctx, user:discord.Member):
if user == None:
user = ctx.author
req = await bot.http.request(discord.http.Route("GET", "/users/{uid}", uid=user.id))
banner_id = req["banner"]
# If statement because the user may not have a banner
if banner_id:
banner_url = f"https://cdn.discordapp.com/banners/{user.id}/{banner_id}?size=1024"
await ctx.send(f"{banner_url}")
Solution 3:[3]
@bot.command(pass_context=True, aliases= ['bn'])
async def banner(ctx, *, user:commands.UserConverter=None):
if user == None:
member = ctx.author
else:
member = user
usr = await bot.fetch_user(member.id)
if usr.banner:
banner = usr.banner.url
bannerEmbed=nextcord.Embed(
title='',
description=f"**[banner]({banner})**",
color=0x000001
)
bannerEmbed.set_author(name=f'{usr.name}#{usr.discriminator}', icon_url=usr.display_avatar.url)
bannerEmbed.set_image(url=banner)
await ctx.send(embed=bannerEmbed)
elif usr.accent_color:
uc = str(usr.accent_color).format(hex).strip('#')
colorEmbed=nextcord.Embed(
title='',
description=f"**[banner]({f'https://singlecolorimage.com/get/{uc}/400x100'})**",
color=0x000001
)
colorEmbed.set_author(name=f'{usr.name}#{usr.discriminator}', icon_url=usr.display_avatar.url)
colorEmbed.set_image(url=f'https://singlecolorimage.com/get/{uc}/400x100')
await ctx.send(embed=colorEmbed)
else:
bnerrEmbed=nextcord.Embed(
title='',
description='banner/color not assigned',
color=0x000001
)
bnerrEmbed.set_author(name=f'{usr.name}#{usr.discriminator}', icon_url=usr.display_avatar.url)
await ctx.send(embed=bnerrEmbed)
@banner.error
async def need_mention(ctx, error):
if isinstance(error, UserNotFound):
await ctx.send("user not found")
else:
print(error)
Here is the second edit for the banner command that works with: nextcord API Wrapper | nextcord's Github
This command will access the user's banner (if applicable) and display it:
If there is no banner but an accent color is assigned, it will display the accent color as the displayed banner.
If no accent color or banner is assigned, the command will send a message to the channel stating that the user has no assigned banner/color.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Karoschal |
| Solution 3 |
