Python deleting a repo from github with request module - python

I do not coding a this situation.
I can create a repository in python using a request.post(), but I can not delete a this repository.
Here is the code:
def deleteRepository(self, repo, name):
headers = {'Accept': 'application/vnd.github.v3+json',
'Authorization': 'token {}'.format(self.token)}
response = requests.delete(self.api_url + '/repos/' + name + repo, headers = headers)
return response.json()

+ name + repo seems strange.
Consider this implementation for instance
def deleteRepository(self,name,username):
response = requests.delete(self.api_url+'/repos/' + username + '/'+name+'?access_token='+self.token)
print(response.status_code)
Note the '/repos/' + username + '/'+name+' part: separators are important for your path segments.
Update June 2021: as explained in "
Deprecating API authentication through query parameters "
If you're currently making an API call similar to
curl "https://api.github.com/user/repos?access_token=my_access_token"
Instead, you should send the token in the header:
curl -H 'Authorization: token my_access_token' https://api.github.com/user/repos
So:
def deleteRepository(self,name,username):
response = requests.delete(self.api_url+'/repos/' + username + '/'+name+', headers={'Authorization': 'token self.token'})
print(response.status_code)

Related

Getting Response Code as 500 when hitting Rest API in Python

I am using requests.get() to invoke the REST api. When i hardcode the URL it is working fine but if i append the account name with URL getting the response code as 500. Please help.
header = {'Authorization': token_type + " " + token, 'Content-Type': 'application/json'}
account_name="test_account"
uri = "https://my_instance.salesforce.com/services/apexrest/account/entitlement?AccountName="+account_name
user_create_res = requests.get(uri, headers=header)
but same code is working when i give,
header = {'Authorization': token_type + " " + token, 'Content-Type': 'application/json'}
uri = "https://my_instance.salesforce.com/services/apexrest/account/entitlement?AccountName=test_account"
user_create_res = requests.get(uri, headers=header)
Try printing the account_name variable using
print(account_name)
Make sure the text logged in the console is the same as the name you tried hard coding.
Though it could also be that the account_name variable is not a String.
I can not say for sure if I don't get more info like where you define the account_name variable.

How to store access_token for more requests on API (Python)

I am making API requests via Python's 'requests'-module. I am getting the access_token, which is a Bearer token.
I've put the token into a variable like this:
def get_token():
url = 'https://myapiurl.com/oauth/token'
payload = {'username':'myusername', 'password':'mypassword'}
headers = {'Content-Type': 'application/json', 'origin': 'https://blabla.com'}
r = requests.post(url, data=json.dumps(payload),headers=headers)
mytoken = r.json()['token_type']
mytokentype = r.json()['access_token']
token_param = str(mytoken) + ' ' + str(mytokentype)
return token_param
The output is a string that has this structure:
Bearer eyJ0eXAiOiJKV1QiLCJhb.....0sImF6cCI6ImVCOEdI
I need this structure for the following GET requests where this access_token is required. I don't want to get a new token everytime I make a new GET-request.
I have issues in finding out how to:
1: store an access_token
2: check if the access_token is valid
3: use this token to make other GET requests on my API.
I am very thankful for any advice.
My answer:
I've put the whole output of my POST request into the variable result.
The structure of my token has to be like this: "Bearer tokenstring".
So I put the type into the variable result_tokentypeand the token string into the variable result_accesstoken.
Finally I put them together into the variable accessToken:
result_tokentype = result["token_type"]
result_accesstoken = result["access_token"]
accessToken = str(result_tokentype) + " " + str(result_accesstoken)
Now that I have the complete string in the right structure, I can use this variable for the next requests, e.g.:
url = "https://myurl.com"
headers = {"Authorization": accessToken, "key1": "value1", "Content-Type": "application/json" }
conn.request("GET", url, headers=headers)
This worked the best for me, here.

curl to python requests conversion

I'm working with Dropbox's python API, trying to convert the following curl command to Python Requests:
curl -X POST https://content.dropboxapi.com/2/files/download \
--header "Authorization: Bearer <ACCESS_TOKEN>" \
--header "Dropbox-API-Arg: {\"path\": \"/Homework/math/Prime_Numbers.txt\"}"
My translation so far:
downloadHeader={"Authorization: " + authorization}
downloadURL = "https://content.dropboxapi.com/2/files/download"
downloadPayload = {"Dropbox-API-Arg": {"path": "/" + dbPATH}}
downloadResponse = requests.post(downloadURL, data=json.dumps(downloadPayload), headers=downloadHeader)
However, when I run this I get the following error:
for header in headers.items():
AttributeError: 'set' object has no attribute 'items'
Can anyone give me some feedback? I'm confident about my authorization value because it's working in a separate request which I'm copy and pasting below:
MDlink = "https://api.dropboxapi.com/2/sharing/get_shared_link_metadata"
authorization = "Bearer " + ACCESS_TOKEN
headers={"Content-Type":"application/json", "Authorization": authorization}
payload = {"url": imageLink}
response = requests.request("POST", MDlink, data=json.dumps(payload), headers=headers)
Thank you very much!
You want this
downloadHeader={"Authorization: " + authorization}
To be
downloadHeader={"Authorization": authorization}
Or more precisely
downloadHeader={"Authorization": "Bearer <ACCESS_TOKEN>"}
Explanation:
{1} # this is a set. It has no .items()
{1: 1} # this is a dict. You can call .items()

Exception Value: HTTP Error 400: Bad Request after a Python/urllib2 request to PayPal Sandbox Site

I'm trying to integrate PayPal REST API in my website. As a first step, I'm trying to translate cURL commands into Python and I'm getting an Exception Value: HTTP Error 400.
The code I'm using (is based on https://stackoverflow.com/a/2003832/2675537):
def basic_authorization(user, password):
s = user + ":" + password
return "Basic " + s.encode("base64").rstrip()
req = urllib2.Request("https://api.sandbox.paypal.com/v1/oauth2/token",
headers = {
"Authorization": basic_authorization("EBWKjlELKMYqRNQ6sYvFo64FtaRLRR5BdHEESmha49TM", "EO422dn3gQLgDbuwqTjzrFgFtaRLRR5BdHEESmha49TM"),
"Accept": "application/json",
"Accept": "*/*",
"User-Agent": "my-python-app/1",
},
data = '{"message":{"body":' + 'grant_type=client_credentials' + '}}' )
f = urllib2.urlopen(req)
return HttpResponse(f)
which is the equivalent (I guess) to:
curl https://api.sandbox.paypal.com/v1/oauth2/token \
-H "Accept: application/json" \
-u "EBWKjlELKMYqRNQ6sYvFo64FtaRLRR5BdHEESmha49TM:EO422dn3gQLgDbuwqTjzrFgFtaRLRR5BdHEESmha49TM" \
-d "grant_type=client_credentials"
And the traceback is here: (Edit: Broken Link)
According to PayPal I should get a response like this:
{"scope":"https://api.paypal.com/v1/payments/.* https://api.paypal.com/v1/vault/credit-card https://api.paypal.com/v1/vault/credit-card/.* https://api.paypal.com/v1/developer/.*","access_token":"OABI8rm75u.5EIuK7.JrI2sLhnv3rhDgLElKAwTfyys","token_type":"Bearer","app_id":"APP-2EJ531395M785864S","expires_in":28800}
Is there an error in my code? Is there a better way to do it?
First of all, I would suggest you not to post your keys in clear text in your code examples.
The error your getting "HTTP Error 400: Bad Request", is due to a badly formed request.
From the docs the format for a request is:
urllib2.Request(url[, data][, headers][, origin_req_host][, unverifiable])
data may be a string specifying additional data to send to the server,
or None if no such data is needed.
headers should be a dictionary, and will be treated as if add_header()
was called with each key and value as arguments.
So your data field is passing a dict instead of string, and it would be a lot more readable
if you separated the fields outside of the Request class. When you have multiple header
fields to fill in, I find it better to use the add_header method as shown below.
import urllib, urllib2
def basic_authorization(user, password):
s = user + ":" + password
return "Basic " + s.encode("base64").rstrip()
url = "https://api.sandbox.paypal.com/v1/oauth2/token"
params = { "grant_type": client_credentials}
data = urllib.urlencode(params)
req = urllib2.Request(url, data)
req.add_header("Authorization",basic_authorization("XXX"))
req.add_header("Accept", "application/json")
req.add_header("User-Agent", "my-python-app/1")
response = urllib2.urlopen(req)

How to send username:password to unittest's app.get() request?

This is part of my unit test in Flask-RESTful.
self.app = application.app.test_client()
rv = self.app.get('api/v1.0/{0}'.format(ios_sync_timestamp))
eq_(rv.status_code,200)
Within the command line I could use curl to send the username:password to the service:
curl -d username:password http://localhost:5000/api/v1.0/1234567
How do I achieve the same within my unit test's get() ?
Since my get/put/post require authentication otherwise the test would fail.
From RFC 1945, Hypertext Transfer Protocol -- HTTP/1.0
11.1 Basic Authentication Scheme
...
To receive authorization, the client sends the user-ID and password,
separated by a single colon (":") character, within a base64 [5]
encoded string in the credentials.string.
...
If the user agent wishes to send the user-ID "Aladdin" and password
open sesame", it would use the following header field:
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
So if you really use http basic authentication you can solution like below, although your curl usage suggests some other authentication scheme.
from base64 import b64encode
headers = {
'Authorization': 'Basic ' + b64encode("{0}:{1}".format(username, password)).decode('utf-8')
}
rv = self.app.get('api/v1.0/{0}'.format(ios_sync_timestamp), headers=headers)
An alternative solution - All credit goes to Doug Black
def request(self, method, url, auth=None, **kwargs):
headers = kwargs.get('headers', {})
if auth:
headers['Authorization'] = 'Basic ' + base64.b64encode(auth[0] + ':' + auth[1])
kwargs['headers'] = headers
return self.app.open(url, method=method, **kwargs)
and then use this method in your tests:
resp = self.request('GET', 'api/v1.0/{0}'.format(ios_sync_timestamp), auth=(username, password))
For Python 3, try the following example:
from base64 import b64encode
headers = {
'Authorization': 'Basic %s' % b64encode(b"username:password").decode("ascii")
}
self.app.get("foo/", headers=headers)
If you'd like to use dynamic variables for username and password, then try something like:
'Basic %s' % b64encode(bytes(username + ':' + password, "utf-8")).decode("ascii")
See also: Python, HTTPS GET with basic authentication

Categories

Resources