error creating event with Meetup's api (Python) - python-requests

I am trying to use Meetup's api to automatically post events on the network, and I am following their guide but I still getting b'Must provide query string.' as a return.
Does anyone know what I may be doing wrong?
import requests
authent_url = "https://api.meetup.com/gql"
params = {
"Authorization" : "Bearer [API KEY HERE]",
}
creating_event = {"mutation": '{createEvent(input: {"groupUrlname": "MY NAME", "title": "Arraial do Cabo", "description": "Trip para arraial", "startDateTime": "2022-09-10 15:00:00.000"}) {event {id} errors {message code field}}}'}
query_by_title = requests.post(authent_url, headers=params, json=creating_event)
query_by_title.content
I don't know what else to do, any help?
EDIT:
Remade the query here and got it
https://splunktool.com/post-graphql-mutation-with-python-requests

Related

Graph API - ResourceNotFound when creating a user

Ive been trying to do this for a couple of days now and ive double checked everything against examples and tried searching my error response but im not able to come up with anything.
Ive succesfully added graph api calls to my appplication already, when I do a GET on the /users endpoint it returns my AD users just fine, the code below is what I am doing to try and create the user but every time i get ResourceNotFound response.
It may we worth noting that at first I was getting an error message where it wasnt stating the resource it couldnt find, but now the error message is showing 'Resource 'User_' does not exist...'
The GUID changes every time suggesting that it is creating that object and then trying to do something with it but then failing on the API somewhere.
Create User Function -
Public Function CreateUser(user As User) As String
Dim app As IConfidentialClientApplication = MsalAppBuilder.BuildConfidentialClientApplication(ClaimsPrincipal.Current)
Dim accountId = ClaimsPrincipal.Current.GetMsalAccountId()
Dim account = app.GetAccountAsync(accountId).Result
Dim result As AuthenticationResult
Dim scopes As String() = {"https://graph.microsoft.com/.default"}
Try
result = app.AcquireTokenSilent(scopes, account).ExecuteAsync().Result
Catch msalEx As MsalUiRequiredException
Return msalEx.Message
Catch ex As Exception
result = app.AcquireTokenForClient(scopes).ExecuteAsync().Result
End Try
Dim client = New HttpClient()
Dim request As New HttpRequestMessage(HttpMethod.Post, "https://graph.microsoft.com/v1.0/users")
request.Headers.Authorization = New AuthenticationHeaderValue("Bearer", result.AccessToken)
Dim json = JsonConvert.SerializeObject(user)
request.Content = New StringContent(json, Encoding.UTF8, "application/json")
Dim response = client.SendAsync(request).Result
If response.Content IsNot Nothing Then
Dim responseString = response.Content.ReadAsStringAsync().Result
Return responseString
End If
Return ""
End Function
Something else I noticed is that the app never contains any users so the scope only token is always called.
After posting here I also requested help from the microsoft support team.
They suggested that i use the graph explorer to try again, so after doing both that and re-sending my request in Insomnia I did in fact get a successful response when using the graph explorer and still BadRequest from Insomnia and code.
The difference between these requests was the Request Body.
What I initially built was using the code sample provided in the graph documentation here (Example 1) - https://learn.microsoft.com/en-us/graph/api/user-post-users?view=graph-rest-1.0&tabs=http
To save you some time this is what it looks like -
POST https://graph.microsoft.com/v1.0/users
Content-type: application/json
{
"accountEnabled": true,
"displayName": "Adele Vance",
"mailNickname": "AdeleV",
"userPrincipalName": "AdeleV#contoso.onmicrosoft.com",
"passwordProfile" : {
"forceChangePasswordNextSignIn": true,
"password": "xWwvJ]6NMw+bWH-d"
}
}
And this is what the request body looks like in graph explorer -
{
"accountEnabled": true,
"city": "Seattle",
"country": "United States",
"department": "Sales & Marketing",
"displayName": "Melissa Darrow",
"givenName": "Melissa",
"jobTitle": "Marketing Director",
"mailNickname": "MelissaD",
"passwordPolicies": "DisablePasswordExpiration",
"passwordProfile": {
"password": "b85dba0d-be1b-a59a-8332-6821b138674d",
"forceChangePasswordNextSignIn": false
},
"officeLocation": "131/1105",
"postalCode": "98052",
"preferredLanguage": "en-US",
"state": "WA",
"streetAddress": "9256 Towne Center Dr., Suite 400",
"surname": "Darrow",
"mobilePhone": "+1 206 555 0110",
"usageLocation": "US",
"userPrincipalName": "MelissaD#{domain}"
}
After changing my code model to match the second request body I now get a successful response in code, and to test the theory I left my old request body in Insomnia and resent the request with a fresh token and it return BadRequest whilst the code returned Success.
I'm not 100% sure what the missing properties are, perhaps just password policies. If Microsoft give me more insight I will update here.
Hopefully this provides someone else with some insight as I really struggled to find information on this one myself.
Try out a few things -
As Tim suggested using the same token and JSON Content and see if you can leverage Postman and call the same API to validate your JSON(request body), URL, and token.
Use jwt.ms and check if your token has all necessary claims.
Make sure you have given required permission to your App.
If you still face same problem, do revert with client-request-id and timestamp so that I can check it better.
Thanks.

The number of keys specified in the URI does not match number of key properties for the resource 'microsoft.graph.bookingAppointment

We are trying to use Graph APIs for Bookings application. In fact, we are customizing
the C# code from the microsoft sample :
https://microsoft.github.io/bookings-samples/
We have the application registration and all the permissions configured in Azure.
Using the BookingsSampleNativeConsole, we are able to query the graphService.BookingBusinesses
as shown below.
var graphService = new GraphService(GraphService.ServiceRoot,
() => authenticationResult.CreateAuthorizationHeader());
Unfortunately none of the other entities gets populated. So we are using the following to query the appointments:
Uri appointUri = new Uri("https://graph.microsoft.com/beta/bookingBusinesses/{id}/appointments");
var appointParams = new UriOperationParameter[]
{
new UriOperationParameter("start", "2020-08-01T00:00:00Z"),
new UriOperationParameter("end", "2020-08-31T00:00:00Z")
};
var resp = graphService.Execute(appointUri, "GET", appointParams);
But this call returns :
An error occurred while processing this request. --->
Microsoft.OData.Client.DataServiceClientException:
{
"error":
{
"code": "BadRequest",
"message": "The number of keys specified in the URI does not match number of key properties for the resource 'microsoft.graph.bookingAppointment'."
}
}
Any idea what we are missing or wrong with appointParams ?
Thanks in advance.
(2)Graph APIs for Bookings has been in beta for quite sometime now. Any idea
when is the probable release date for version 1.0 ?
Ajit19

Sending headers to post request

I have this python code that does not work as expected.
import requests
import json
API_ENDPOINT = "https://lkokpdvhc4.execute-api.us-east-1.amazonaws.com/mycall"
data = {'mnumber':'9819838466'}
r = requests.post(url = API_ENDPOINT, data = json.dumps(data))
print (r.text)
This will return an error:
{"stackTrace": [["/var/task/index.py", 5, "handler", "return
mydic[code]"]], "errorType": "KeyError", "errorMessage": "''"}
When I test the API using Amazon console's gateway, I get the expected output (i.e. string like "mumbai"). It means this is client side issue. I have confirmed this by using "postman" as well that returns the same error as mentioned above. How do I send correct headers to post request?
You can create a dictionary with the headers such as
headers = {
"Authorization": "Bearer 12345",
"Content-Type": "application/json",
"key" : "value"
}
Then at the point of making the request pass it as a keyword argument to the request method i.e .post() or .get() or .put
This will be
response = requests.post(API_ENDPOINT, data=json.dumps(data), headers=headers)

Python Request Session JIRA REST post http 405

Using python requests session I can connect to JIRA and retrieve issue information ...
session = requests.Session()
headers = {"Authorization": "Basic %s" % bas64_val}
session.post(jira_rest_url, headers=headers)
jira = session.get(jira_srch_issue_url + select_fields)
# select_fields = the fields I want from the issue
Now I'm trying to post a payload via the JIRA API, using a fixed issue url e.g. "https://my_jira_server.com:1234/rest/api/latest/issue/KEY-9876"
Which should be a case of the following, given: https://developer.atlassian.com/jiradev/jira-apis/about-the-jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-example-edit-issues
payload = { "update": {
"fixVersions": [ {"set": "release-2.139.0"} ]
}}
posted = session.post(jira_task_url, data=payload)
# returns <Response [405]>
# jira_task_url = https://my_jira_server.com:1234/rest/api/latest/issue/KEY-9876
But this doesn't appear to work! Looking into the http 405 response, suggests that my payload is not properly formatted! Which notably, is the not easiest thing to diagnose.
What am I doing wrong here? Any help on this would be much appreciated.
Please note, I am not looking to use the python jira module, I am using requests.session to manage several sessions for different systems i.e. JIRA, TeamCity, etc..
Found the solution! I had two problems:
1) The actual syntax structure should have been:
fix_version = { "update": { "fixVersions": [ {"set" : [{ "name" : "release-2.139.0" }]}]
2) To ensure the payload is actually presented as JSON, use json.dumps() which takes an object and produces a string (see here) AND set 'content-type' to 'application/json':
payload = json.dumps(fix_version)
app_json = { 'content-type': 'application/json' }
session.put(https://.../rest/api/latest/issue/KEY-9876, headers=app_json, data=payload)
Rather than trying to define the JSON manually!

google-bigquery how to get datasetlist with https get?

I'm trying to get dataset list from bigquery webserver with https get
following the documentation here:
https://developers.google.com/bigquery/docs/reference/v2/datasets/list
i'm using slightly modified code from:
http://code.google.com/p/qt-google-bigquery/source/browse/manager_bigquery.cpp
getDatasetsList(QString strProjectID)
{
QString url = QString("https://www.googleapis.com/bigquery/v2/projects/%1/datasets?key=%2").arg(str_ProjectID).arg(this->api_key);
//Also tried without ?key= part
QNetworkRequest request;
request.setUrl( QUrl(url) ); //this also urlencodes
request.setRawHeader("Content-Type", "application/json");
request.setRawHeader("Authorization", (QString("Bearer %1").arg(m_Access_Token)).toLatin1());
//here i post the request as a http get asynchronously
}
i get back this error message:
Reply = "{
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Required parameter is missing"
}
],
"code": 400,
"message": "Required parameter is missing"
}
}
Note:
I managed to run a query and get the results, so my access token seems to be valid, what am i doing wrong here?
SOLVED
Ah, actually the problem was in my coding, not the request, i posted it as a http post, not a get.
See answer in comment by original poster above - but basically make sure you are using GET instead of the POST method for an API call to list datasets. Other BigQuery API methods use POST, PUT, or PATCH.
https://developers.google.com/bigquery/docs/reference/v2/datasets/list

Resources