Basecamp 3 API - basic projects.json call - python

I'm a Python user, beginner level. I'm trying to follow this instruction on Basecamp 3. Documentation: https://github.com/basecamp/bc3-api
I've successfully gone through the authorization step and was able to retrieve the access token (which consists of 3 keys: access_token, expires_in and refresh_token.
Now i'm trying to pull some actual data from Basecamp, and the most basic call is to https://3.basecampapi.com/999999999/projects.json (with 99999999 being my account number, which I have).
The instruction has an example in curl: curl -H "Authorization: Bearer $ACCESS_TOKEN" -H 'User-Agent: MyApp (yourname#example.com)' https://3.basecampapi.com/999999999/projects.json
But I cannot translate this to Python. I tried many methods of passing the keys to the header call but none works. Can anyone help me out?
Code:
url = "3.basecampapi.com/99999999/projects.json"
headers = {'Content-Type': 'application/json',
'User-Agent': 'MyApp (myemail#gmail.com)',
'access_token': 'Access_Token_String',
'expires_in': '1209600',
'refresh_token': 'Refresh_token_string'}
result = requests.post(url, headers=headers)

This is an old question, but posting an answer for anyone who happens to stumble upon this.
url = f'3.basecampapi.com/{PROJECT_ID}/projects.json'
headers = {'User-Agent': 'MyApp (myemail#gmail.com)',
'Content-Type': 'application/json; charset=utf-8',
'Authorization': f'Bearer {ACCESS_TOKEN}'
response = requests.get(url, headers=headers)
Then view the output via response.json()

Related

spotify api returning illegal request is there something wrong with my request code?

i tried using subprocess with a cURL command but as the number of the app users grow some other error happens
headers = {
'Authorization': 'Basic ZjJmOWJl...ZDllZDc=',
'Content-Type': 'application/json',
}
data = 'grant_type=authorization_code&code=AQDOad...a7vsDpWldA&redirect_uri=https%3A%2F%2Fusername.github.io%2F'
response1 = requests.get(topTracks,headers=headers,data=data).text
e = open('ttt.txt','w')
e.write(response1)
e.close()
Can i have a basic example of how to do an api request ?

Python requests PUT

I need to send a PUT request with authentication in one time.
When I use Postman for that and input
headers = {'Authorization': 'Basic Token', 'Content-Type': 'application/json'}
Authorization = Basic Auth Username = 'login' Password = 'pass'
Body = data
everything goes well.
If I try to write request in python:
req = r.put(url, headers={'Authorization': 'Basic Token', 'Content-Type': 'application/json'}, auth=HTTPBasicAuth('login','password'), data=data)
I get response 400 Bad Request
Whats wrong with my request?
I don't know if this works for your case, but I did use Basic authentication a while ago to authenticate with the Reddit API.
Here's my code:
import requests
client_auth = requests.auth.HTTPBasicAuth("put something here","put something here")
headers = {"User-Agent": "manage your reddit easily by u/0xff"}
code = "ajkldjfalkdjflajfd;lakdjfa"
data = {
"code":code,
"grant_type":"authorization_code",
"redirect_uri":"http://127.0.0.1:3000/authorize_callback"
}
r = requests.post("https://www.reddit.com/api/v1/access_token", auth=client_auth, data=data, headers=headers);
print(r.content)
Just make the appropriate changes for your case and try it.
You are setting authorization information twice, and different HTTP libraries will handle this conflict in different ways.
HTTP Basic Authorization uses the Authorization header, encoding the username and password (separated by :) as base64 and setting the header to the value Basic plus space plus the base64 encoded string. You are telling both POSTman and requests to set the Authorization header to the string Basic Token and to use a username and password for Basic Auth, so the clients will have to make a choice between these two options.
Trying this out in requests version 2.25.1 I see that the auth information will win here:
>>> from requests import Session, Request
>>> from requests.auth import HTTPBasicAuth
>>> req = Request(
... "PUT",
... "http://example.com",
... headers={
... 'Authorization': 'Basic Token',
... 'Content-Type': 'application/json'
... },
... auth=HTTPBasicAuth('login','password'),
... data=b"{}"
... )
>>> session = Session()
>>> prepped = session.prepare_request(req)
>>> from pprint import pp
>>> pp(dict(prepped.headers))
{'User-Agent': 'python-requests/2.25.1',
'Accept-Encoding': 'gzip, deflate',
'Accept': '*/*',
'Connection': 'keep-alive',
'Authorization': 'Basic bG9naW46cGFzc3dvcmQ=',
'Content-Type': 'application/json',
'Content-Length': '2'}
The above session creates a prepared request so I can inspect the effect of the auth argument on the headers given to the request, and as you can see the Authorization header has been set to a base64 value created from the login and password pair.
It looks like Postman will do the same, the UI even tells you so:
You didn't share any details about what web service you are using or what expectations that service has for headers or request contents. If this a OAuth2-protected service, then you should not confuse obtaining a token with using that token for subsequent requests to protected URLs. For a grant_type="password" token request, it could be that the server expects you to use the username and password in a Basic Auth header, but it may also expect you to use client_id and client_secret values for that purpose and put the username and password in the POST body. You'll need to carefully read the documentation.
Other than that, you could replace your destination URL with an online HTTP echo service such as httpbin. The URL https://httpbin.org/put will give you a JSON response with the headers that the service received as well as the body of your request.
Further things you probably should be aware of:
requests can encode JSON data for you if you use the json argument, and if you do, the Content-Type header is generated for you.
You don't need to import the HTTPBasicAuth object, as auth=(username, password) (as a tuple) works too.

How to refetch the access token in a Python script automatically after it expires?

so I am working on fetching data from an api using access token only. I have created two python scripts, one for fetching the token and the other for fetching data. I have created a common variable 'token' for both scripts. However when token expires in 15 minutes, I have to restart the script manually. Is there an solution for this problem?
Auth Code:
response = requests.request("POST", url, headers=headers, data=payload)
token = response.json()['access_token']
Fetch Sample:
response2 = requests.request("GET", qurl, headers=headers2, data=payload2)
r2=response2.json()
payload={}
headers = {
'Host': 'proxy.sample.com',
'Accept': 'application/vnd.sample.v1+json',
'Authorization': 'Basic
MFQxOE5HYmFsUURGYzBnWkh6b3ZwZVJkN0a1Y3BMQ3w6dnwnamFZa3Ric2p4OUFPUg==',
'Accept-Encoding': 'br;q=1.0, gzip;q=0.9, deflate;q=0.8',
'Accept-Language': 'en-US;q=1.0, ar-US;q=0.9',
'Content-Type': 'application/json',
'User-Agent': 'SampleApp/3.37.0 (com.sample.mobile.consumer; build:3.#; iOS
14.4.1) Alamofire/5.2.2',
'access_token': token
Note: I don't want more than one instance of the script at once.
Just a thought, assuming you're using a loop you could use except.
Therefore when the error procs the code will log you back in and continue
e.g.
while True:
try:
{script here}
except {ErrorType}:
print('token expired')
{relogin code}
continue

HTTP headers - Requests - Python

I am trying to scrape a website in which the request headers are having some new (for me) attributes such as :authority, :method, :path, :scheme.
{':authority':'xxxx',':method':'GET',':path':'/xxxx',':scheme':'https','accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8','accept-encoding':'gzip, deflate, br','accept-language':'en-US,en;q=0.9','cache-control':'max-age=0',GOOGLE_ABUSE_EXEMPTION=ID=0d5af55f1ada3f1e:TM=1533116294:C=r:IP=182.71.238.62-:S=APGng0u2o9IqL5wljH2o67S5Hp3hNcYIpw;1P_JAR=2018-8-1-9', 'upgrade-insecure-requests': '1', 'user-agent': 'Mozilla/5.0(WindowsNT6.1;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/68.0.3440.84Safari/537.36', 'x-client-data': 'CJG2yQEIpbbJAQjEtskBCKmdygEI2J3KAQioo8oBCIKkygE=' }
I tried passing them as headers with http request but ended up with error as shown below.
ValueError: Invalid header name b':scheme'
Any help would be appreciated on understanding and guidance on using them in passing request.
EDIT:
code added
import requests
url = 'https://www.google.co.in/search?q=some+text'
headers = {':authority':'xxxx',':method':'GET',':path':'/xxxx',':scheme':'https','accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8','accept-encoding':'gzip, deflate, br','accept-language':'en-US,en;q=0.9','cache-control':'max-age=0','upgrade-insecure-requests': '1', 'user-agent': 'Mozilla/5.0(WindowsNT6.1;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/68.0.3440.84Safari/537.36', 'x-client-data': 'CJG2yQEIpbbJAQjEtskBCKmdygEI2J3KAQioo8oBCIKkygE=' }
response = requests.get(url, headers=headers)
print(response.text)
Your error comes from here (python's source code)
Http headers cannot start with a semicolon as RFC states.
:authority, :method, :path, :scheme are not http headers
https://en.wikipedia.org/wiki/List_of_HTTP_header_fields
':method':'GET'
defines http request method
https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods
and
:authority, :path, :scheme
are parts of URI https://en.wikipedia.org/wiki/Uniform_Resource_Identifier#Generic_syntax

How to make Raw REST Call for Azure using Python

I am trying to make REST Call for azure using python,
Have created Access token using ADAL in python.
But getting Error called "provided Authorization header is in invalid format."
Here is the code for that:
import adal
import requests
token_response = adal.acquire_token_with_username_password(
'https://login.windows.net/abcd.onmicrosoft.com',
'user-name',
'password'
)
access_token = token_response.get('accessToken')
url = 'https://management.azure.com/subscriptions/{subscription- id}/providers/Microsoft.Network/virtualnetworks?api-version=2015-06-15'
headers = {'Content-Type': 'application/json',
'Authorization': access_token}
response = requests.get(url=url,headers = headers)
print(response.status_code)
print(response.text)
Can anyone tell me how the access-token should look like?
And is this the correct way to generate token for REST in python?
I am reffering this link for above code:
https://msdn.microsoft.com/en-us/library/azure/mt163557.aspx
As #GauravMantri said, the format of the value of the header Authorization is Bearer <access-token> that you can refer to the section Calling ARM REST APIs of the doc "Resource Manager REST APIs".
For example in the section above.
GET /subscriptions/SUBSCRIPTION_ID/resourcegroups?api-version=2015-01-01 HTTP/1.1
Host: management.azure.com
Authorization: Bearer YOUR_ACCESS_TOKEN
Content-Type: application/json
You would need to prepend Bearer to your token. Something like:
headers = {'Content-Type': 'application/json',
'Authorization': 'Bearer ' + access_token}

Categories

Resources