Tiktok api /user/info endpoint - python

Edit: Since this question is getting a good amount of views, I'd like to let you all know before you waste hours of your life on the upload endpoint that it currently requires you to manually click confirm in the app. So it doesn't allow you to fully automate uploads. To anyone which this saves time, you're welcome :)
Currently trying to implement the TikTok api into one of my projects. However having a few difficulties with a specific endpoint. Not sure if its an error on my part or on Tiktoks.
Upon making the below request I am recieving an invalid request body error message. I have followed their documentation to the T so unsure why this is happening?
https://developers.tiktok.com/doc/login-kit-user-info-basic
data = {
"access_token": access_token,
"open_id": open_id,
"fields": [
"open_id",
"union_id",
"avatar_url",
"avatar_url_100",
"avatar_url_200",
"avatar_large_url",
"display_name"
]
}
user_info = requests.post("https://open-api.tiktok.com/user/info/", data=data)
print(user_info.json())
{'data': {}, 'error': {'code': 6007055, 'log_id': '', 'message': 'invalid request body'}}

Use json parameter instead of data
import requests
data = {
"access_token": access_token,
"open_id": open_id,
"fields": [
"open_id",
"union_id",
"avatar_url",
"avatar_url_100",
"avatar_url_200",
"avatar_large_url",
"display_name"
]
}
user_info = requests.post("https://open-api.tiktok.com/user/info/", json=data)
print(user_info.json())

Related

Amazon Seller Central SP API ERROR - 'code': 'InvalidInput', 'message': 'Invalid request parameters', 'details': ''

Updating inventory in the seller central, using their API, suddenly stopped working for Japan and Australia.
I was told by the account holder that Amazon's response to this problem was to just look at the documentation which doesn't help at all since the documentation hasn't changed. The request body that is failing is ...
{
"feedType": "POST_FLAT_FILE_INVLOADER_DATA",
"inputFeedDocumentId": "[actual document id returned by AWS when document was uploaded]",
"path": "/feeds/2021-06-30/feeds",
"marketplaceIds": ["A39IBJ37TRP1C6"],
"MarketplaceIds": ["A39IBJ37TRP1C6"]
}
After editing the python-amazon-sp-api library so the request would match the documentation exactly I sent the following request.
{
"feedType": "POST_FLAT_FILE_INVLOADER_DATA",
"inputFeedDocumentId": "[actual document id returned by AWS when document was uploaded]",
"marketplaceIds": ["A39IBJ37TRP1C6"]}'
}
The response document for both requests is
"errors": [
{
"code": "InvalidInput",
"message": "Invalid request parameters",
"details": ""
}
]
}
This response is pretty useless since the details are empty.
The documentation does say to send the file with content type text/tab-separated-values; charset=iso-8859-1 but when I did that they return an internal error, try again. This problem doesn't happen when I send content type text/tsv. Feeds for other countries are still working with this code, but this isn't working with Japan or Australia and Amazon support on this issue is useless! Is there any work-around to get this feed to be accepted by Amazon?

login into Spotify through python requests module

I've been trying to connect my Spotify account using the requests module and I came across a problem
later on I tried to manipulate it on my Python code
import requests
URL = 'https://accounts.spotify.com/login/password'
payload = {
"username": "example#gmail.com",
"password": "123456",
"remember" : True
}
response = requests.post(URL , json=payload)
print(response.status_code)
OUTPUT : 415
what went wrong ?
I don't think this is how you should interact with Spotify from code.
It has an API and you should use tokens for authentication or anything else from password.
Anyway you can try setting the correct media type when making the request:
URL = 'https://accounts.spotify.com/login/password'
payload = {
"username": "example#gmail.com",
"password": "123456",
"remember" : True
}
headers = { 'Content-Type':'application/x-www-form-urlencoded' }
response = requests.post(URL , json=payload, headers=headers)
you cannot use this url to send post request as it has "recaptchaToken" which you need pass in your payload which is getting generated dynamically. Hence it is not a good idea to use this approach.
Instead you can use API to achieve the same.
https://github.com/plamere/spotipy

How to send json POST request using requests if the website uses jwt?

i am trying to send POST request to login to this URL
, i first checked the network tab and found out the the post request is being sent to this
url : https://api-my.te.eg/api/user/login?channelId=WEB_APP
and the request payload is:
{
"header":{
"timstamp":0,
"customerId":null,
"msisdn":null,
"messageCode":null,
"responseCode":"1200",
"responseMessage":"Your Session has been expired, please sign in to continue",
"locale":null,
"referenceId":null,
"channelId":null,
"responeAdditionalParameters":null
},
"body":null
}
Here is the code :
import requests
import calendar
import time
#Here i tried to send a generated timestamp, idk if this is needed or not
ts = calendar.timegm(time.gmtime())
loginUrl = 'https://api-my.te.eg/api/user/login?channelId=WEB_APP'
values = {
"msisdn": MobileNumberID,
"timestamp": str(ts),
"locale": "Ar"
}
data = {
"password": PasswordID
}
url = requests.post(loginUrl , data=data , headers=values)
print(url.text)
I looked at the site and in the body they are also passing a header property in the data
So you should use
data = {
"header": {
"msisdn": "024568478",
"timestamp": "1592337873",
"locale": "Ar"
},
"body": {
"password": "PJGkRJte5ntnKt9TQ8XM3Q=="
}
}
and in headers you should pass the native headers probably something like:
headers={'Content-Type': 'application/json', }
but i also see by when you log into this site they pass a jwt argument in the headers. Looks like its some sort of built in security. So it looks like you can not use this API. Its only for the backend of this site.
Did you search the site to see if they have API documentation, maybe their is written how you can calculate the value for jwt?
EDIT:
When you get the login working this is. How to use sessions in python requests:
s = requests.Session()
data = {"login":"my_login", "password":"my_password"}
url = "http://example.net/login"
r = s.post(url, data=data)
If you do not get arround the jwt. You can uses Selenium in python. It works by automating a webbrowser. So you can open chrome tell it wich page to load, fill in your login form and read the html of elements in the browser. This will work on 95% of the websites. Some even have protections against it. Some sites use cloudflare, they are protected from selenium automation.

How to properly use POST in an API request for Earth Explorer

So first of all thanks, I'm really new to python and I am trying to understand APIs, I'm currently trying to log in into /inventory/json/v/1.4.1/<request_code>?jsonRequest=<json_request_content> which is the Earth Explorer API, and the first step is to Login, and according to the documentation I am supposed to use POST instead of GET, so here is what I got so far, and it works but this is what I
import requests
import requests
user = 'xxxxx'
psword = 'xxxxx'
input_data= {'username':user,'password':psword,'catalogId':'EE'}
test=requests.post('https://earthexplorer.usgs.gov/inventory/json/v/1.4.0/login?jsonRequest=input_data)')
print(test.text)
print(test.status_code)
{
"errorCode": "AUTH_ERROR",
"error": "Passing credentials via URL is not permitted - use a POST request",
"data": null,
"api_version": "",
"access_level": "guest",
"executionTime": 0
}
200
I have no idea what to do, thank you so much. This is the documentation for the earth explorer API, thank you so much https://earthexplorer.usgs.gov/inventory/documentation/json-api?version=1.4.1#login
I have encountered the same problem while working with Earth Explorer API and managed to solve it by reading usgs package code. Basically, the problem is that you must send the request body as a string. That is, your request body must look like this when printed
{
"jsonRequest": "{\"username\": \"???\", \"password\": \"???\", \"catalogId\": \"???\"}"
}
You can achieve this using
import json
import requests
req_params = {
'username': '???',
'password': '???',
'catalogId': '???',
}
req_txt = json.dumps(req_params)
req_body = {
'jsonRequest': req_txt,
}
resp = requests.post('<LOGIN URL HERE>', req_body)
This code is actually taken from usgs package I mentioned, so you should refer to it if you have any additional questions.

Azure Analysis rest api : 401 Unauthorized. "Authentication failed."

I'm trying to make a data partition refresh (post) following this azure documentation : https://learn.microsoft.com/en-us/azure/analysis-services/analysis-services-async-refresh
Either with post or get I got 401 Unauthorized (Even when the service is Off !).
I got the token from azure AD (ServicePrincipalCredential).
I added the AD as Analysis Services Admins (https://learn.microsoft.com/en-us/azure/analysis-services/analysis-services-server-admins)
I gave the owner role to AD in Analysis Services IAM.
it worked with Analysis Services management rest api (https://learn.microsoft.com/en-us/rest/api/analysisservices/operations/list) With the same authentification (got code response 200)
My python code :
from azure.common.credentials import ServicePrincipalCredentials
import requests
credentials = ServicePrincipalCredentials(client_id="ad_client_id",
secret="ad_secret",
tenant="ad_tenant")
token = credentials.token
url = "https://westeurope.asazure.windows.net/servers/{my_server}/models/{my_model}/refreshes"
test_refresh = {
"Type": "Full",
"CommitMode": "transactional",
"MaxParallelism": 1,
"RetryCount": 1,
"Objects": [
{
"table": "my_table",
"partition": "my_partition"
}
]
}
header={'Content-Type':'application/json', 'Authorization': "Bearer {}".format(token['access_token'])}
r = requests.post(url=url, headers=header, data=test_refresh)
import json
print(json.dumps(r.json(), indent=" "))
Response I got :
{
"code": "Unauthorized",
"subCode": 0,
"message": "Authentication failed.",
"timeStamp": "2019-05-22T13:39:03.0322998Z",
"httpStatusCode": 401,
"details": [
{
"code": "RootActivityId",
"message": "aab22348-9ba7-42c9-a317-fbc231832f75"
}
]
}
I'm hopeless, could you please give me somes help to make this clear ?
Finally I resolved the issue.
I had wrong token. The api expect an OAuth2.0 authentification token (The Azure analysis services rest api documentation ins't very clear about the way to get one)
For thoses will encounter the same issu there is the way to get one.
from adal import AuthenticationContext
authority = "https://login.windows.net/{AD_tenant_ID}"
auth_context = AuthenticationContext(authority)
oauth_token = auth_context.acquire_token_with_client_credentials(resource="https://westeurope.asazure.windows.net", client_id=AD_client_id, client_secret=AD_client_id)
token = oauth_token['accessToken']
Documentation about this :
https://learn.microsoft.com/en-us/python/api/adal/adal.authentication_context.authenticationcontext?view=azure-python#acquire-token-with-client-credentials-resource--client-id--client-secret-
https://github.com/AzureAD/azure-activedirectory-library-for-python/wiki/ADAL-basics
Most likely your token is not right.
Have you tried validating your token? Use something like http://calebb.net/
I see some examples of ServicePrincipalCredentials that stipulate the context or resource like this:
credentials = ServicePrincipalCredentials(
tenant=options['tenant_id'],
client_id=options['script_service_principal_client_id'],
secret=options['script_service_principal_secret'],
resource='https://graph.windows.net'
Good samples here:
https://www.programcreek.com/python/example/103446/azure.common.credentials.ServicePrincipalCredentials
I think the solution is try a couple more things that make sense and follow the error details.
You need token which has resource (audience) set to https://*.asazure.windows.net
For token validation I like https://jwt.io
Also if you want to automate this properly you have two options
Either by Logic Apps
or with Azure Data Factory
Both of which I have very detailed posts on if you want to check them out
https://marczak.io/posts/2019/06/logic-apps-refresh-analysis-services/
https://marczak.io/posts/2019/06/logic-app-vs-data-factory-for-aas-refresh/

Categories

Resources