Can I use hexcode of colours to retrieve spotify playlists - python

So the user enters the hexcode of a colour and the program uses that to get Spotifyfy playlist.
e.g user enters "red" the program will get "energetic" playlist from Spotify.
Hexcode = input("Please enter Colour: ")
Im just not sure how to set up the retrieval part from Spotify
These are the Snippets I have:
curl -X "GET" "https://api.spotify.com/v1/browse/categories/dinner/playlists?country=SE&limit=10&offset=5" -H "Accept: application/json" -H "Content-Type: application/json" -H "Authorization: Bearer
if Hexcode ==:
Yellow = #FFCC00
Blue = #03025D
Red = #FF0000
Green = #339900
Purple = #580C6D
$.ajax({
url: "https://api.spotify.com/v1/users/" + $("#username").val() + "/playlists",
headers: {
Authorization: "Bearer my_OAuth_Token",
Host: "api.spotify.com"
},
accepts: "application/json",
type: "GET",
success: function (data) {
var count = data.items.length;
for (var i = 0; i < aantal; i++) {
$("#playlists").append('<option>' + data.items[i].name + '</option>');
}
},
error: function (data) {
$("#playlists").append("<option>error</option>");
}
});
They're not set up properly and are for different things. I got kind of lost and wasn't really sure what to do.

Related

wordpress: wp_remote_post can't pass body to the fast api, while from api docs and python requests no issue, error msg: value is not a valid dict, 422

background: I am trying to make a fastapi and wordpress plugin which will use api in localhost (both sits on the same server), i have developed the api and its working perfectly fine through swagger ui and python request library however can't use it in the plugin through wp_remote_post
code for the api:
from fastapi import FastAPI
from pydantic import BaseModel
from api.article import add_article, html_format_data
app = FastAPI()
class PostData(BaseModel):
links: list
title: str
#app.post('/create_post/')
def create_post(post_data: PostData):
html_format = html_format_data(post_data.links, post_data.title) # list of dicts
if add_article(post_data.title, html_format):
return {"status": 201, "success": True}
else:
return {"error"}
python request code:
import requests
data = {
"title": "gaming",
"links": [
{
"id": "video id 1",
"thumbnail": "url of thumbnail 1,
"title": "title of video 1"
},
{
"id": "video id 2",
"thumbnail": "url of thumbnail 2 ,
"title": "title of video 2"
}
]
}
res = requests.post('http://127.0.0.1:5000/create_post/', json=data)
print(res.content)
same success through swagger ui:
curl -X 'POST' \
'http://127.0.0.1:5000/create_post/' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"links": [
{
"id": "shortand",
"thumbnail": "shortand",
"title": "shortand"
},
{
"id": "shortand",
"thumbnail": "shortand",
"title": "shortand"
}
],
"title": "gaming"
}'
but when i do it through wordpress plugin which code is below:
function create_post( $data, $query ) {
$url = 'http://127.0.0.1:5000/create_post/';
$arguments = array(
'method' => 'POST',
'body' => json_encode(array(
"links" => $data,
"title" => $query
)),
'header' => array(
'Content-Type' => 'application/json',
'accept' => 'application/json'
)
);
$response = wp_remote_post( $url, $arguments );
// echo '<script>console.log(`data: ' . $arguments["body"] . '`)</script>';
echo '<script>console.log(`' . json_encode($response) . '`)</script>';
}
i get this error in the console:
{"headers":{},"body":"{"detail":[{"loc":["body"],"msg":"value is not a valid dict","type":"type_error.dict"}]}","response":{"code":422,"message":"Unprocessable Entity"},"cookies":[],"filename":null,"http_response":{"data":null,"headers":null,"status":null}}
i am new to wordpress and php.
i did consult these solutions but nothing seem to work as i am doing in from php.
POST request response 422 error {'detail': [{'loc': ['body'], 'msg': 'value is not a valid dict', 'type': 'type_error.dict'}]}
FastAPI - "msg": "value is not a valid dict" in schema request
EDIT
i did the below as suggested BUT still getting the same error, heres the php code:
function create_post( $data, $query ) {
$url = 'http://127.0.0.1:5000/create_post/';
$data_arr = array("links" => $data,"title" => $query);
$data_obj = (object) $data_arr;
$body = json_encode( $data_obj );
$arguments = array(
'method' => 'POST',
'body' => $body,
'header' => array(
'Content-Type' => 'application/json',
'accept' => 'application/json'
)
);
$response = wp_remote_post( $url, $arguments );
echo '<script>console.log(`' . $body . '`)</script>';
echo '<script>console.log(`' . json_encode($response) . '`)</script>';
}
SOLVED
lol my issue was a idiotic, i missed the "s" in headers so it want any json anymore because it cant see headers so it couldnt find it json thats why it was giving the error not a valid dict.
When handling JSON from php, we sometimes run into problems with the distinction between objects and associative arrays.
Try casting your body array as an object before giving it to json_encode(), something like this:
$body = json_encode( (object)
array(
"links" => $data,
"title" => $query
));
print_r ($body); //debugging: examine JSON to pass to web service
$arguments = array(
'method' => 'POST',
'body' => $body,
'header' => array(
'Content-Type' => 'application/json',
'accept' => 'application/json'
)
);
$response = wp_remote_post( $url, $arguments );

Elasticsearch Search Query using python subprocess: Illegal Argument Exception

I am trying to run a curl command using the run command in the subprocess module in python. But it is failing.
However, the curl command for my elasticsearch search query API is working fine-
curl -k XGET -H "Content-Type: application/json" -H "Authorization: ApiKey Q2txZ2FvSUJ6Nlcwa3pjbnh0NUM6enBidjdNLTdRQVNhc0tuTEk5UEZmZw==" 'https://internal-a02c1b85dade940ef871b0b6d1e65191-1270244841.us-west-2.elb.amazonaws.com:9200/_search?index=.fleet-enrollment-api-keys-7&size=20&pretty' -d '{"query": {"match": {"_id": "c8a537a9-7f98-489b-8f8b-de2450c67ce6"}},"fields" : ["_id", "_index"]}'
This is the code that I am trying to run-
import json
from builtins import int
from pydantic import BaseModel, Field
from typing import List, Dict
from subprocess import PIPE, run
def elasticsearch_search_query(host: str,
port: int,
api_key: str,
path: str,
query: dict,
index: str,
size: int,
fields: List):
es_path = host + ":" + str(port) + path +"?index="+index+"&"+str(size)+"&pretty"
es_header = "Authorization: ApiKey" + " " + api_key
es_dict = {"query": query, "fields": fields}
es_json = json.dumps(es_dict)
es_replaced = " "+"'"+ es_json.replace("'", "\"")+"'"
result = run(["curl", "-k", "-XGET", "-H", "Content-Type: application/json", "-H",
es_header,
es_path,
"-d",
es_replaced]
# ,stdout=PIPE, stderr=PIPE, universal_newlines=True, shell=False
)
print(es_path, es_header, es_replaced)
print(result.stdout)
elasticsearch_search_query(host="https://internal-a02c1b85dade940ef871b0b6d1e65191-1270244841.us-west-2.elb.amazonaws.com:9200/_search", api_key="Q2txZ2FvSUJ6Nlcwa3pjbnh0NUM6enBidjdNLTdRQVNhc0tuTEk5UEZmZw==",
port=9200, size=5, query={"match": {"_id": "c8a537a9-7f98-489b-8f8b-de2450c67ce6"}}, fields=["_id", "_index"], path="/_search",index=".fleet-enrollment-api-keys-7")
Here is the error-
{
"error" : {
"root_cause" : [
{
"type" : "illegal_argument_exception",
"reason" : "request [/_search:9200/_search] contains unrecognized parameter: [5]"
}
],
"type" : "illegal_argument_exception",
"reason" : "request [/_search:9200/_search] contains unrecognized parameter: [5]"
},
"status" : 400
}
https://internal-a02c1b85dade940ef871b0b6d1e65191-1270244841.us-west-2.elb.amazonaws.com:9200/_search:9200/_search?index=.fleet-enrollment-api-keys-7&5&pretty Authorization: ApiKey Q2txZ2FvSUJ6Nlcwa3pjbnh0NUM6enBidjdNLTdRQVNhc0tuTEk5UEZmZw== '{"query": {"match": {"_id": "c8a537a9-7f98-489b-8f8b-de2450c67ce6"}}, "fields": ["_id", "_index"]}'
None
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 350 100 350 0 0 10294 0 --:--:-- --:--:-- --:--:-- 10294
curl: (3) nested brace in URL position 12:
'{"query": {"match": {"_id": "c8a537a9-7f98-489b-8f8b-de2450c67ce6"}}, "fields": ["_id", "_index"]}'
UPDATE
Output of repr(result):
CompletedProcess(args=['curl', '-k', '-XGET', '-H', 'Content-Type: application/json', '-H', 'Authorization: ApiKey Q2txZ2FvSUJ6Nlcwa3pjbnh0NUM6enBidjdNLTdRQVNhc0tuTEk5UEZmZw==', 'https://internal-a02c1b85dade940ef871b0b6d1e65191-1270244841.us-west-2.elb.amazonaws.com:9200:9200/_search?index=.fleet-enrollment-api-keys-7&size=5&pretty', '-d', '{"query": {"match": {"_id": "c8a537a9-7f98-489b-8f8b-de2450c67ce6"}}, "fields": ["_id", "_index"]}'], returncode=3)
Since the error was
contains unrecognized parameter: [5]
The problem is not in the query but in the way you construct es_path. Instead of
&"+str(size)+
it should be
&size="+str(size)+
UPDATE:
Also from what I see your URL now looks like this
https://internal-a02c1b85dade940ef871b0b6d1e65191-1270244841.us-west-2.elb.amazonaws.com:9200:9200/_search?index=.fleet-enrollment-api-keys-7&size=5&pretty
and it's wrong for the following reasons:
the port is specified twice
the index is not at the right location
First, host should just be this (i.e. without port and path)
host="https://internal-a02c1b85dade940ef871b0b6d1e65191-1270244841.us-west-2.elb.amazonaws.com"
Then you can build the URL like this instead:
es_path = host + ":" + str(port) + "/" + index + path +"?size="+str(size)+"&pretty"
i.e. it should look like this instead:
https://internal-a02c1b85dade940ef871b0b6d1e65191-1270244841.us-west-2.elb.amazonaws.com:9200/.fleet-enrollment-api-keys-7/_search?size=5&pretty

Opsgenie powershell alert post not working

I have successfully made an alert post using Python, but cannot get my powershell alert creation to work. I just get a wall of HTML in my response and no alert creation. Message is the only required field.
Here's what I'm using and it does not work
$api = "XXX"
$URI = "https://api.opsgenie.com/v2/alerts"
$head = #{"Authorization" = "GenieKey $api"}
$body = #{
message = "testing";
responders =
]#{
name = "TEAMNAMEHERE";
type = "team"
}]
} | ConvertTo-Json
$request = Invoke-RestMethod -Uri $URI -Method Post -Headers $head -ContentType "application/json" -Body $body
$request
Here is my python code I made and it works just fine.
import requests
import json
def CreateOpsGenieAlert(api_token):
header = {
"Authorization": "GenieKey " + api_token,
"Content-Type": "application/json"
}
body = json.dumps({"message": "testing",
"responders": [
{
"name": "TEAMNAMEHERE",
"type": "team"
}
]
}
)
try:
response = requests.post("https://api.opsgenie.com/v2/alerts",
headers=header,
data=body)
jsontemp = json.loads(response.text)
print(jsontemp)
if response.status_code == 202:
return response
except:
print('error')
print(response)
CreateOpsGenieAlert(api_token="XXX")
EDIT: So I've figured out it has something to do with my "responders" section. It has something to do with the [ ]...but I haven't been able to figure out what exactly. If I remove them, it wont work. If I turn the first one around, it won't work. I can get the alert to create successfully, however I keep getting the following error:
] : The term ']' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At \\file\Tech\user\powershell scripts\.not working\OpsGenieAlert.ps1:7 char:17
+ ]#{
+ ~
+ CategoryInfo : ObjectNotFound: (]:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
You need to convert your $body to JSON
$api = "XXX"
$URI = "https://api.opsgenie.com/v2/alerts"
# Declare an empty array
$responders = #()
# Add a new item to the array
$responders += #{
name = "TEAMNAMEHERE1"
type = "team1"
}
$responders += #{
name = "TEAMNAMEHERE2"
type = "team2"
}
$body = #{
message = "testing"
responders = $responders
} | ConvertTo-Json
$invokeRestMethodParams = #{
'Headers' = #{
"Authorization" = "GenieKey $api"
}
'Uri' = $URI
'ContentType' = 'application/json'
'Body' = $body
'Method' = 'Post'
}
$request = Invoke-RestMethod #invokeRestMethodParams

No exact amount estimate price for UberX

Currently within the app, requesting a UberX instantly give you a exact quote price but in the Python API, I couldn't find it. I can only find the range of the cost. Where is the exact quote at?
Try to use "POST /v1.2/requests/estimate"
Example Request
curl -X POST \
-H 'Authorization: Bearer <TOKEN>' \
-H 'Accept-Language: en_US' \
-H 'Content-Type: application/json' \
-d '{
"start_latitude": 37.7752278,
"start_longitude": -122.4197513,
"end_latitude": 37.7773228,
"end_longitude": -122.4272052
}' "https://api.uber.com/v1.2/requests/estimate"
I suggest you use "product_id" as well - to get the price for the product you need. Otherwise, if none is provided, it will default to the cheapest product for the given location.
You will get the response like:
{
"fare": {
"value": 5.73,
"fare_id": "d30e732b8bba22c9cdc10513ee86380087cb4a6f89e37ad21ba2a39f3a1ba960",
"expires_at": 1476953293,
"display": "$5.73",
"currency_code": "USD",
"breakdown": [
{
"type": "promotion",
"value": -2.00,
"name": "Promotion"
},
{
"type": "base_fare",
"notice": "Fares are slightly higher due to increased demand",
"value": 7.73,
"name": "Base Fare"
}
]
},
"trip": {
"distance_unit": "mile",
"duration_estimate": 540,
"distance_estimate": 2.39
},
"pickup_estimate": 2
}
Related to Pyton SDK - Please check: https://developer.uber.com/docs/riders/ride-requests/tutorials/api/python. You need to authenticate your user, and then get a product you want to use, and then get upfront fare (if product support this: upfront_fare_enabled field set to true). And after that you can book a ride. Code how to do it is in doc link I have sent as well:
# Get products for a location
response = client.get_products(37.77, -122.41)
products = response.json.get('products')
product_id = products[0].get('product_id')
# Get upfront fare and start/end locations
estimate = client.estimate_ride(
product_id=product_id,
start_latitude=37.77,
start_longitude=-122.41,
end_latitude=37.79,
end_longitude=-122.41,
seat_count=2
)
fare = estimate.json.get('fare')
# Request a ride with upfront fare and start/end locations
response = client.request_ride(
product_id=product_id,
start_latitude=37.77,
start_longitude=-122.41,
end_latitude=37.79,
end_longitude=-122.41,
seat_count=2,
fare_id=fare['fare_id']
)
request = response.json
request_id = request.get('request_id')
# Request ride details using `request_id`
response = client.get_ride_details(request_id)
ride = response.json
# Cancel a ride
response = client.cancel_ride(request_id)
ride = response.json

REST API File Upload - Porting Python to PowerShell

Could anyone help me perform the following Python process in PowerShell?
json_res = json.loads(res.text,object_pairs_hook=collections.OrderedDict)
files = {'file':open(image_path,'rb').read()}
_data = json_res.items()
_data[1] = ('upload_params',_data[1][1].items())
upload_file_response = requests.post(json_res['upload_url'],data=_data[1][1],files=files,allow_redirects=False)
Here is my PowerShell to get the initial json response used in the json_res object using:
$initialization_parameters = #{
"name" = $($image.Name);
"size" = $($image.Length);
"content_type" = $(if ($image.Extension -match 'jp*g') { "image/jpeg" } elseif ($image.Extension -match 'png') { "image/png" } elseif ($image.Extension -match 'gif') { "image/gif" } else { "image/jpeg" });
"parent_folder_path" = "profile pictures";
"as_user_id" = $("sis_user_id:" + $file_id)
}
$initialization_parameters = $initialization_parameters | ConvertTo-Json
$initial_response = Invoke-RestMethod -Uri $avatars_base_url -Headers $headers -Body $initialization_parameters -ContentType "application/json" -Method POST
I am not sure how to do the next request though and add the image for upload - I have tried sending a byte array OR just the local file path, but those don't seem to work.
Specifically, I would like to know how to best mimic the 2nd and 5th lines of the Python code I have there in PowerShell.
Any help would be appreciated.
I think this is what you need to do. If not, hopefully it will at least put you on the right track...
$FileContent = [System.IO.File]::ReadAllBytes($Image.FullName)
$UploadInfo #{
"File" = $Image.Name
"Data" = [System.Convert]::ToBase64String($FileContent)
}
$FileUpload = Invoke-JSONMethod -uri $Upload_URL -ContentType "application/json" -Method POST -Body (ConvertTo-Json $UploadInfo) -AcceptType "application/json"

Categories

Resources