How to set the Doc Id with Firebase REST API - python

Is there a way to manually create a docId when inserting a document into Firestore?
The following Python3 code will insert a new document in Firestore with an auto-generated docId.
import requests
import json
project_id = 'MY_PROJECT_NAME'
web_api_key = 'MY_WEB_API_KEY'
collection_name = 'MY_COLLECTION_NAME'
url = f'https://firestore.googleapis.com/v1/projects/{project_id}/databases/(default)/documents/{collection_name}/?key={web_api_key}'
payload = {
'fields': {
'title': { 'stringValue': 'myTitle' },
'category': { 'stringValue': 'myCat' },
'temperature': { 'doubleValue': 75 }
}
}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
response = requests.post(url, data=json.dumps(payload), headers=headers)
response_dict = json.loads(response.content)
for i in response_dict:
print(f'{i}: {response_dict[i]}')
In case anyone else wants to use this code in the future, to get a Web API key, go to Google Cloud Platform > APIs & Services > Credentials > Create Credentials > API key, then copy the value it generates here.
Thanks,
Ryan

answered in Google Cloud Firestore REST API createDocument auto genarates ID documentId should be added as a query parameter when document is created
So for the code in the question, just url should be changed with the same body:
url = f'https://firestore.googleapis.com/v1/projects/{project_id}/databases/(default)/documents/{collection_name}?documentId={your_custom_doc_id}&key={web_api_key}'

To set a custom document ID, you only need to append the name to the URL path after the respective collection. This is similar to how the document reference works where the path must point to the desired location.
From the documentation:
https://firestore.googleapis.com/v1/projects/YOUR_PROJECT_ID/databases/(default)/documents/cities/LA

Related

Rancher API: Unauthorized 401: must authenticate

I'm trying to communicate with rancher API, tried different combinations, getting the same result every time:Unauthorized 401: must authenticate
steps to reproduce:
1)Create Rancher API key and secret
2)Create a simple script that uses them to deploy a test workload.
import requests
api_url = "https://myrancherurl.com/v3/project/c-m-qh7tkqn4/jobs"
access_key = "token-zmdpqs"
secret_key = "fr9v6z9xxfqdgmjv2k9z44zvx6mlrandomtoke"
token=access_key+":"+secret_key
# Set the API token
headers = { "Authorization": "Bearer "+token }
# Set the payload for the API request
payload = {
"name": "my-job",
"jobConfig": {
"image": "nginx:latest",
"command": ["nginx", "-g", "daemon off;"],
"restartPolicy": {
"name": "Never"
}
}
}
# Send the API request to create the job
response = requests.post(api_url, json=payload, headers=headers)
# Print the API response
print(response.json())
I'm not 100% sure what exaclty is "Project id", so I tried different combinations, results are the same. I have the impression, that additional config has to be done on rancher side, but can't find any info.
Any ideas?
I've tried also using the official python library, but it seems outdated(and also returns the same erro)
Every object in the Rancher API has an id. Project is a like a group used to organize various namespaces, and workloads.
There are three types of clients that are used to interact with the Rancher API.
Management (Used to interact with general objects not tied to any cluster/project)
Cluster (Used to interact with objects that are tied to a specific cluster)
Project (Used to interact with objects that are tied to a specific project)
Sample code:
pip install git+https://github.com/rancher/client-python.git#master
import rancher
rancher_url = 'https://rancher.example.com/v3'
rancher_token = 'token-abcde:abcdefghijklmnopqrstuvwxyz0123456789'
rancher_verify_ssl_certs = True
management_client = rancher.Client(
url=rancher_url,
token=rancher_token,
verify=rancher_verify_ssl_certs
)
clusters_info = management_client.list_cluster(name='leo-downstream')
my_cluster = clusters_info.data[0]
projects_info = management_client.list_project(name='Default')
default_project = projects_info.data[0]
default_project_url = default_project.links['self'] + '/schemas'
default_project_client = rancher.Client(url=default_project_url, token=rancher_token, verify=False)
containers = [
{
'name': 'one',
'image': 'nginx',
}
]
default_project_client.create_workload(
name='test-workload-creation',
namespaceId='default',
scale=1,
containers=containers
)

Github API number of watch over time

I am trying to fetch the number of watches over time using Python, I have tried "https://api.github.com/repos/octocat/hello-world/subscription" that is listed on the Github API webpage, but seems no longer work, I am a bit confused. I am just trying to get "created_at" under subscription. Any suggestions? Thank you.
EDIT - as per your first comment and extra requirements: Unfortunately I do not think it is possible to get watchers over time, you can however get the stargazers over time, an example using GitHub's GraphQL API is below. To do so you can use the following:
import requests
MY_TOKEN = my_token
REPO_NAME = repo_name
REPO_OWNER = repo_owner
query = f'''{{
repository(name: "{REPO_NAME}", owner: "{REPO_OWNER}") {{
watchers {{
totalCount
}}
stargazers(first: 100) {{
totalCount
edges {{
starredAt
}}
}}
}}
}}
'''
headers = {"Authorization": f"token {MY_TOKEN}"}
request = requests.post("https://api.github.com/graphql", json={"query": query}, headers=headers)
print(request.json())
Which will output a result like the following:
{
"data": {
"repository": {
"watchers": {
"totalCount": 1594
},
"stargazers": {
"totalCount": 53952,
"edges": [
{
"starredAt": "2016-08-15T18:39:55Z"
},
{
"starredAt": "2016-08-15T19:14:32Z"
}
]
}
}
}
}
You can easily try out GitHub's GraphQL API in the explorer they provide (one click to run a query). Just use the following query as an example (and replace the repo name and owner as you wish):
{
repository(name: "repo_name", owner: "repo_owner") {
watchers {
totalCount
}
stargazers(first:100) {
totalCount
edges {
starredAt
}
}
}
}
Note you should now be careful for pagination (see first:... parameter).
I guess for privacy reasons the date when a user added a repository to watch is not public. The only way that I have found to get that date is using the user scope instead of repo scope, using the following call:
https://api.github.com/users/your_username/subscriptions
Remember you have to be authenticated using a private token
To get the number of watchers you can do this:
#get number of watchers
url = f"https://api.github.com/repos/{git_owner_repository}/{git_repository_name}"
response = requests.get(url, auth=(username, GITHUB_TOKEN))
response.raise_for_status()
response_dict = response.json()
watchers = response_dict['watchers_count']
#get all the watchers:
url = f"https://api.github.com/repos/octocat/hello-world/subscribers?simple=yes&per_page={watchers}"
response_watcher = requests.get(url, auth=(username, GITHUB_TOKEN))
response_watcher.raise_for_status()
response_watcher = response.json()
for watcher in response_watcher:
user_url = watcher['url']
watcher_name = watcher['login']
response_user = requests.get(user_url, auth=(username, GITHUB_TOKEN))
response_user.raise_for_status()
response_dict_user = response.json()
created_at= response_dict_user['created_at']
print(f"watcher name: {watcher_name}, created_at: {created_at}")

Error 404 api azure translator basic program python

I started a translator project on azure.
I copy the simple test code.
import os, requests, uuid, json
subscription_key = 'KEY_IN_PORTAL_AZURE'
endpoint = 'URL_IN_PORTAL_AZURE'
path = '/translate?api-version=3.0'
params = '&from=fr&to=en'
constructed_url = endpoint + path + params
headers = {
'Ocp-Apim-Subscription-Key': subscription_key,
'Content-type': 'application/json',
'X-ClientTraceId': str(uuid.uuid4())
}
body = [{
'text' : 'Bonjour'
}]
request = requests.post(constructed_url, headers=headers, json=body)
response = request.json()
print(json.dumps(response, sort_keys=True, indent=4,
ensure_ascii=False, separators=(',', ': ')))
I change the key and the endpoint but the program return
{
"error": {
"code": "404",
"message": "Resource not found"
}
}
I delete the service and i retry same thing
There're 2 errors in the sample code.
Error 1: for the endpoint, use this one instead of copying the one from azure portal:
endpoint = 'https://api.cognitive.microsofttranslator.com/'
Error 2: in headers, please add Ocp-Apim-Subscription-Region, and it's value is the region of the Cognitive Services resource. Like below:
'Ocp-Apim-Subscription-Region':'EastUS'
You can get the region from azure portal, the screenshot is as below:
And I tested it at my side, it worked. The result as below:

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.

Trouble getting contact folders through microsoft graph api

I'm having difficulties getting Microsoft Graph to return two test Contact Folders that I have set up named Test and Test 2.
When I use v1.0:
headers = {'Authorization': 'Bearer ' + token, 'Accept': 'application/json'}
url = 'https://graph.microsoft.com/v1.0/me/contactFolders'
response = requests.get(url,headers=headers)
response_data = response.json()
print(response_data)
I get a blank value in the response:
{
'#odata.context': "https://graph.microsoft.com/v1.0/$metadata#users('jacobdansey%40hotmail.com')/contactFolders",
'value': []
}
When I use the Beta, I get this which at least returns something but not what I'm looking for:
{
'#odata.context': "https://graph.microsoft.com/beta/$metadata#users('jacobdansey%40hotmail.com')/contactFolders",
'value': [{
'id': '*ID*',
'parentFolderId': '*ParentID*',
'displayName': 'Contacts',
'wellKnownName': 'contacts'
}, {
'id': '*ID*',
'parentFolderId': '*ParentID*',
'displayName': 'Skype Contacts',
'wellKnownName': 'skypecontacts'
}]
}
I know I am connecting properly because when I ask for just contacts from https://graph.microsoft.com/v1.0/me/contacts, it returns the correct answer.
Any help would be greatly appreciated, thanks!
EDIT: Is there a difference between contact folders and contact lists?
i am assuming you want access to folder to get the contacts, if thats the case then you can directly get the contacts of that folder changing the get url
https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_list_contacts

Categories

Resources