(Pyrebase) error : orderBy must be a valid JSON encoded path - python

I use firebase and my JSON(Firebase) is as below.
I want to retrieve the key values(288xxx) by using busStopName values.
My code is as below. I'll make an example with '윤정사앞'
# Retriving id by using value
def getIdByName(db, name) :
bus = db.child("busStops").order_by_child("busStopName").equal_to(name).get()
print(bus.key())
...
...
getIdByName(db, "윤정사앞")
My ideal result of this code was 288000001.
But there are errors, which are 'Bad Request' and 'orderBy must be a valid JSON encoded path'.
Please help me...

You have to go into rules in firebase, and update rules that you can do it.
In rules, in firebase, you need to update this:
{
"rules": {
".read": ...
".write": ...
"busStops": {
".indexOn": "busStopName"
}
}
}

Related

Jira API : when using PUT call getting "no single-String constructor/factory method"

I was trying to update a custom field on a Jira ticket using Jira API, following this Jira Documentation. however, I am getting the below error.
{'errorMessages': ['Can not instantiate value of type [simple type, class com.atlassian.jira.rest.v2.issue.IssueUpdateBean] from JSON String; no single-String constructor/factory method']}
this is my code:
data = {'update': {'customfield_25305': [{'set': [{'value': '1c1a07d49af1b1cde8a1a7bd93cbbeef8efd50c9'}, {'value': 'c6f1e31ce0138cba658f769accaac729bebc42d6'}]}]}}
data = json.dumps(json.dumps(data)) #because the API accepts only strings enclosed in double quotes
upload = requests.put(url, headers=headers, data=data)
print(upload.json())
as per the documentation, I tried "/editmeta" the custom field I am trying to update is editable and has the following attributes.
{'required': False, 'schema': {'type': 'string', 'custom': 'com.atlassian.jira.plugin.system.customfieldtypes:textfield', 'customId': 25305}, 'name': 'Commit ID(s)', 'fieldId': 'customfield_25305', 'operations': ['set']}
Not sure what I am doing wrong here, any help would be appreciated!
Tried jira documentation
and searched through the Jira community none of the answers helped, everything points to malformed data but the data that I am passing is as per documentation.
the end result would be a 204 status code.
I think is a matter of single quotes.
As far as I remember, for valid JSON it should be double quotes.
{
"update": {
"customfield_25305": [{
"set": [{
"value": "1c1a07d49af1b1cde8a1a7bd93cbbeef8efd50c9"
}, {
"value": "c6f1e31ce0138cba658f769accaac729bebc42d6"
}]
}]
}
}
I use to do a online validator tool to my JSON strings when I got stuck.
E.g. https://jsonlint.com/ (first result on google)
I was able to resolve the issue, the proper formatting for data is as below:
{"fields": {"customfield_25305": "\"1c1a07d49af1b1cde8a1a7bd93cbbeef8efd50c9\", \"c6f1e31ce0138cba658f769accaac729bebc42d6\", \"1c1a07d49af1b1cde8a1a7bd93cbbeef8efd50c9\""}}

Check if entry exists in Firebase Realtime Databse (Python)

I am currently trying to retrieve login information from my Realtime DB in Firebase.
As an example, I want to detect whether the provided username already exists in the db.
Here is a code snippet I'm attemping to work with.
ref.child("Users").order_by_child("Username").equal_to("Hello").get()
It does not however work, and instead displays this message:
firebase_admin.exceptions.InvalidArgumentError: Index not defined, add ".indexOn": "Username", for path "/Users", to the rules
Is there something wrong with my code snippet or should I use a different alternative?
As the error suggests, you need to add ".indexOn": "Username" in your security rules as shown below:
{
"rules": {
"Users": {
".indexOn": "Username",
// ... rules
"$uid": {
// ... rules
}
}
}
}
Checkout the documentation for more information.

How to validate JSON request body before sending PUT request in python

It's when I send a PUT request to my API endpoint from python with a JSON request body I receive empty request body, because sometimes It's containing special characters which is not supported by JSON.
How can I sanitize my JSON before sending my request?
I've tried with stringify and parsing json before I sent my request!
profile = json.loads(json.dumps(profile))
My example invalid json is:
{
"url": "https://www.example.com/edmund-chand/",
"name": "Edmund Chand",
"current_location": "FrankfurtAmMainArea, Germany",
"education": [],
"skills": []
}
and My expected validated json should be:
{
"url": "https://www.example.com/edmund-chand/",
"name": "Edmund Chand",
"current_location": "Frankfurt Am Main Area, Germany",
"education": [],
"skills": []
}
If you're looking for something quick to sanitize json data for limited fields i.e. current_location, you can try something like the following below:
def sanitize(profile):
profile['current_location'] = ', '.join([val.strip() for val in profile['current_location'].split(',')])
return profile
profile = sanitize(profile)
The idea here is that you would write code to sanitize each bits in that function and send it your api or throw exception if invalid etc.
For more robust validation, you can consider using jsonschema package. More details here.
With that package you can validate strings and json schema more flexibly.
Example taken from the package readme:
from jsonschema import validate
# A sample schema, like what we'd get from json.load()
schema = {
"type" : "object",
"properties" : {
"url" : {"type" : "string", "format":"uri"},
"current_location" : {"type" : "string", "maxLength":25, "pattern": "your_regex_pattern"},
},
}
# If no exception is raised by validate(), the instance is valid.
validate(instance=profile, schema=schema)
You can find more infor and types of available validation for strings here.
Thank you #Rithin for your solution but that one seems more coupled with one field of the whole JSON.
I found a solution to replace it with below example code which works for any field:
profile = json.loads(json.dumps(profile).replace("\t", " "))

Updating Zapier Storage programmatically

I have been working with the Zapier storage api through the store.zapier.com endpoint and have been successful at setting and retrieving values. However I have recently found a need to store more complex information that I would like to update over time.
The data I am storing at the moment looks like the following:
{
"task_id_1": {"google_id": "google_id_1", "due_on": "2018-10-24T17:00:00.000Z"},
"task_id_2": {"google_id": "google_id_2", "due_on": "2018-10-23T20:00:00.000Z"},
"task_id_3": {"google_id": "google_id_3", "due_on": "2018-10-25T21:00:00.000Z"},
}
What I would like to do is update the "due_on" child value of any arbitrary task_id_n without having to delete and add it again. Reading the API information at store.zapier.com I see you can send a patch request combined with a specific action to have better control over the stored data. I attempt to use the patch request and the "set_child_value" action as follows:
def update_child(self, parent_key, child_key, child_value):
header = self.generate_header()
data = {
"action" : "set_child_value",
"data" : {
"key" : parent_key,
"value" : {child_key : child_value}
}
}
result = requests.patch(self.URL, headers=header, json=data)
return result
When I send this request Zapier responds with a 200 status code but the storage is not updated. Any ideas what I might be missing?
Zapier Store doesn't seem to be validating the request body past the "action" and "data" fields.
When you make a request with the "data" field set to an array, you trigger a validation error that describes the schema for the data field (What a way to find documentation for an API! smh).
In the request body, the data field schema for "set_child_value" action is:
{
"action" : {
"enum": [
"delete",
"increment_by",
"set_child_value",
"list_pop",
"set_value_if",
"remove_child_value",
"list_push"
]
},
"data" : {
"key" : {
"type": "object"
},
"values" : {
"type": "object"
}
}
}
Note that it's "values" and not "value"
I was able to update specific child values by modifying my request from a PATCH to a PUT. I had to do away with the data structure of:
data = {
"action" : "set_child_value",
"data" : {
"key" : parent_key,
"value" : {child_key : child_value}
}
and instead send it along as:
data = {
parent_key : {child_key : child_value}
}
My updated request looks like:
def update_child(self, parent_key, child_key, child_value):
header = self.generate_header()
data = {
parent_key : {child_key : child_value}
}
result = requests.put(self.URL, headers=header, json=data)
return result
Never really resolved the issue with the patch method I was attempting before, it does work for other Zapier storage methods such as "pop_from_list" and "push_to_list". Anyhow this is a suitable solution for anyone who runs into the same problem.

400 Error while trying to POST to JIRA issue

I am trying to set the 'transition' property in a JIRA issue from whatever it is, to completed(which according to the doc is 10000). According to the documentation, this error is 'If there is no transition specified.'
Also I have used ?expand=transitions.fields to verify that 10000 is for complete.
using these docs
https://docs.atlassian.com/jira/REST/latest/#api/2/issue-doTransition
https://jira.atlassian.com/plugins/servlet/restbrowser#/resource/api-2-issue-issueidorkey-transitions/POST
Here is my request
url = 'http://MYURL/rest/api/2/issue/ISSUE-ID/transitions'
payload1 = open('data3.json', 'r').read()
payload = json.loads(payload1)
textFile = requests.post(url, auth=('username', 'password'), json=payload)
The contents on my data3.json file are
{
"transition": 10000
}
edit: I also changed my JSON to this and I get a 500 error
{
"transition": {
"id": "10000"
}
}
The error I get
{"errorMessages":["Can not instantiate value of type [simple type,classcom.atlassian.jira.rest.v2.issue.TransitionBean] from JSON integral number;no single-int-arg constructor/factory method (through reference chain:com.atlassian.jira.rest.v2.issue.IssueUpdateBean[\"transition\"])"]}400
I'm pretty confident that my issue is in my json file since I have used GET in the code above this snippit multiple times, but I could be wrong.
Possible cause - https://jira.atlassian.com/browse/JRA-32132
I believe the issue I was having was a process flow one. I cannot jump right from my issue being opened, to 'completed'. However, I can go from the issue being created to 'Done'.
{
"transition": {
"name": "Done",
"id": "151"
}
}
As this does what I need, I will use it. If I find how to make ticket complete I will post back.
Also, I think the fact we customize our JIRA lead to my getting 'Completed' as a valid transition even though it wasn't.
Yes, you're right that the JSON is wrong, it's not even a valid json since the value is not a number, string, object, or array. The doc says:
The fields that can be set on transtion, in either the fields
parameter or the update parameter can be determined using the
/rest/api/2/issue/{issueIdOrKey}/transitions?expand=transitions.fields
resource.
So you need to do a get request on /rest/api/2/issue/{issueIdOrKey}/transitions?expand=transitions.fields to get the list of possible values and then set that in the json
{
"transition": {
"id" : "an_id_from_response"
}
}

Categories

Resources