I have been looking for solution regarding passing of session Cookies. Below are my codes in Robot Framework
Settings
Library String
Library OperatingSystem
Library Collections
Library RequestsLibrary
Library requests
***Variables ***
${base_url} https://api.company.net
${email} operator1#datavalidation.org
${password} Company2021
&{headers} Content-Type=application/json X-Requested-With=XMLHttpRequest
*** Test Cases ***
Session | Login
Login
Session | My
My_Profile
*** Keywords ***
Login
&{auth_dict}= Create Dictionary email ${email} password ${password}
Create Session loginsession ${base_url} verify=True
${response}= POST On Session loginsession /session/login json=${auth_dict}
Log ${response.json()}
#VALIDATION
${status}= Convert To String ${response.status_code}
Should Be Equal ${status} 200
${body}= Convert To String ${response.content}
Should Contain ${body} true #"status"
Should Contain ${body} abf60345-4043-4f1e-94b0-a307f9209beb #"uuid"
#GET SESSION COOKIE VALUE
${Session_cookie}= Get From Dictionary ${response.cookies} PHPSESSID
&{Cookie_value}= Create Dictionary PHPSESSID ${Session_cookie}
Set Suite Variable &{Cookie_value}
My_Profile
Create Session mysession ${base_url} cookies=&{Cookie_value} verify=True
${response}= GET On Session mysession /session/me
Log ${response.json()}
As you can see, I extracted the Cookie in (Session | Login) and tried to pass it onto the following test cast (Session | My). Although, I tried to follow the syntax, but still I'm unable to access the API with the Session Cookie. I look forward for open suggestions.
Thank you.
I got the following output-
20210225 18:40:51.355 : INFO :
POST Request : url=https://api.company.net/session/login
path_url=/session/login
headers={'User-Agent': 'python-requests/2.25.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '68', 'Content-Type': 'application/json'}
body=b'{"email": "operator1#company.org", "password": "Company2021"}'
20210225 18:40:51.355 : INFO :
POST Response : url=https://api.company.net/session/login
status=200, reason=OK
headers={'Date': 'Thu, 25 Feb 2021 17:40:50 GMT', 'Content-Type': 'application/json,...'PHP/7.2.34', 'Set-Cookie': 'PHPSESSID=567ta9n28tudq00f09r9g33qfc; path=/',, PUT, POST, DELETE, OPTIONS', 'Access....'Strict-Transport-Security': 'max-age=31536000;'}
body={"ok":true,"status":200,"data":{"uuid":"abf60345-4043-4f1e-94b0-a307f9209beb",...}
20210225 18:40:51.355 : INFO : ${response} = <Response [200]>
20210225 18:40:51.355 : INFO : {'ok': True, 'status': 200, 'data': {'uuid': 'abf60345-4043-4f1e-94b0-a307f9209beb',...}
20210225 18:40:51.355 : INFO : ${status} = 200
20210225 18:40:51.355 : INFO : ${body} = {"ok":true,"status":200,"data":{"uuid":"abf60345-4043-4f1e-94b0-a307f9209beb",...}
20210225 18:40:51.355 : INFO : ${Session_cookie} = 567ta9n28tudq00f09r9g33qfc
20210225 18:40:51.355 : INFO : &{Cookie_value} = { PHPSESSID=567ta9n28tudq00f09r9g33qfc }
20210225 18:40:51.355 : INFO : &{Cookie_value} = { PHPSESSID=567ta9n28tudq00f09r9g33qfc }
Ending test: Operator.Session | Login
Starting test: Operator.Session | Me
20210225 18:40:51.355 : INFO : Creating Session using : alias=mesession, url=https://api.company.net, headers={}, cookies={'PHPSESSID': '567ta9n28tudq00f09r9g33qfc'}, auth=None, timeout=None, proxies=None, verify=True, debug=0
20210225 18:40:51.555 : INFO :
GET Request : url=https://api.company.net/session/me
path_url=/session/me
headers={'User-Agent': 'python-requests/2.25.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Cookie': 'PHPSESSID=567ta9n28tudq00f09r9g33qfc'}
body=None
20210225 18:40:51.555 : INFO :
GET Response : url=https://api.company.net/session/me
status=403, reason=FORBIDDEN
headers={'Date': 'Thu, 25 Feb 2021 17:40:50 GMT', 'Content-Type': 'application/json; charset=UTF-8', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', .... *"}
body={"ok":false,"status":403,"data":null,"errors":"5.95.67.44 not allowed"}
20210225 18:40:51.586 : FAIL : HTTPError: 403 Client Error: FORBIDDEN for url: https://api.company.net/session/me
Ending test: Operator.Session | Me
I was able to solve it by Creating a session in the first Test Case and the pass the alias to the following Test Case (Instead of extracting the Cookies and passing them in the next case.)
Here is the way I did it-
*** Variables ***
${base_url} https://api.company.net
${email} operator1#datavalidation.org
${password} Company2021
&{headers} Content-Type=application/json X-Requested-With=XMLHttpRequest
*** Test Cases ***
Session | Login
&{auth_dict}= Create Dictionary email ${email} password ${password}
Create Session api ${base_url} verify=True
${test_uri} Set Variable /session/login
${response} POST On Session api ${test_uri} json=${auth_dict} headers=${headers}
Session | Me
${response} GET On Session api /session/me headers=&{headers}
Related
I am trying out sample code here https://github.com/DiUS/pact-workshop-dotnet-core-v3 with PactNet - 4.3.0. The only change I have made to the sample code is that i am not working with provider states in the test and instead have the required state set as part of controller only.
While it works fine on OSX when i try it on windows (Windows Server 2019 Standard) I get the following error -
PactNet.Exceptions.PactFailureException: Pact verification failed
PactNet.Exceptions.PactFailureException
Pact verification failed
at PactNet.Verifier.InteropVerifierProvider.Execute()
at PactNet.Verifier.PactVerifierSource.Verify()
at tests.ProductApiTestsWithoutBroker.EnsureProviderApiHonoursPactWithConsumer() in C:\repos\ProofOfConcepts\Pact-Product-api\ProviderTests\ProductApiTestsWithoutBroker.cs:line 47
at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)
at System.Reflection.MethodInvoker.Invoke(Object obj, IntPtr* args, BindingFlags invokeAttr)
Getting to pact verification
Starting verification...
Pact verification failed
Verifier Output
---------------
Verifying a pact between ApiClient and ProductService
A valid request for all products
returns a response which
has status code 200 (FAILED)
includes headers
"Content-Type" with value "application/json; charset=utf-8" (FAILED)
has a matching body (FAILED)
Failures:
1) Verifying a pact between ApiClient and ProductService - A valid request for all products
1.1) has a matching body
expected 'application/json;charset=utf-8' body but was 'text/html'
1.2) has status code 200
expected 200 but was 400
1.3) includes header 'Content-Type' with value 'application/json; charset=utf-8'
Expected header 'Content-Type' to have value 'application/json; charset=utf-8' but was 'text/html'
There were 1 pact failures
Verifier Logs
-------------
2023-02-14T20:36:14.433512Z INFO ThreadId(33) pact_verifier: Running provider verification for 'A valid request for all products'
2023-02-14T20:36:14.433752Z INFO ThreadId(33) pact_verifier::provider_client: Sending request to provider at http://localhost:9001/
2023-02-14T20:36:14.433771Z INFO ThreadId(33) pact_verifier::provider_client: Sending request HTTP Request ( method: GET, path: /api/products, query: None, headers: None, body: Missing )
2023-02-14T20:36:14.456312Z INFO ThreadId(33) pact_verifier::provider_client: Received response: HTTP Response ( status: 400, headers: Some({"cache-control": ["no-store"], "via": ["1.1 ForcepointCGCluster"], "date": ["Tue", "14 Feb 2023 20:36:32 GMT"], "content-type": ["text/html"], "connection": ["close"], "content-language": ["en"], "content-length": ["666"]}), body: Present(666 bytes, text/html) )
2023-02-14T20:36:14.456421Z INFO ThreadId(33) pact_matching: comparing to expected response: HTTP Response ( status: 200, headers: Some({"Content-Type": ["application/json; charset=utf-8"]}), body: Present(130 bytes) )
2023-02-14T20:36:14.457552Z WARN ThreadId(33) pact_matching::metrics:
Please note:
We are tracking events anonymously to gather important usage statistics like Pact version and operating system. To disable tracking, set the 'PACT_DO_NOT_TRACK' environment variable to 'true'.
2023-02-14T20:36:14.495312Z WARN ThreadId(33) rustls::conn: Sending fatal alert DecodeError
I am using .NET 7 and i tried including PactNet.Windows nuget package but it did not help. Also does not look like long Windows path issue to me here. Any pointers would be very helpful here. Thanks in advance,
Solution:
Update PactNet package to the latest version.
Check the configuration of the environment in which you are running the tests. Ensure that the Content-Type and Content-Encoding headers are set correctly in the response.
Check the code of the API to make sure it is returning the correct response headers and body.
I am tying to access my comments on other videos. But I didn't understand that what is wrong with the request. I put youtube.force-ssl scope.
(Pdb) request = self.service.commentThreads().list(part="id,replies,snippet", channelId="UCxz_B5DVTdZV5c0JLctjqUA")
INFO __init__.py line:49 2022-09-19 21:23:55,044 - file_cache is only supported with oauth2client<4.0.0
(Pdb) request.execute()
*** googleapiclient.errors.HttpError: <HttpError 400 when requesting https://youtube.googleapis.com/youtube/v3/commentThreads?part=id%2Creplies%2Csnippet&channelId=UCxz_B5DVTdZV5c0JLctjqUA&alt=json returned "The API server failed to successfully process the request. While this can be a transient error, it usually indicates that the request's input is invalid. Check the structure of the <code>commentThread</code> resource in the request body to ensure that it is valid.". Details: "[{'message': "The API server failed to successfully process the request. While this can be a transient error, it usually indicates that the request's input is invalid. Check the structure of the <code>commentThread</code> resource in the request body to ensure that it is valid.", 'domain': 'youtube.commentThread', 'reason': 'processingFailure', 'location': 'body', 'locationType': 'other'}]">
(Pdb) request.headers
{'accept': 'application/json', 'accept-encoding': 'gzip, deflate', 'user-agent': '(gzip)', 'x-goog-api-client': 'gdcl/2.52.0 gl-python/3.8.10', 'content-length': '0'}
(Pdb) request.uri
'https://youtube.googleapis.com/youtube/v3/commentThreads?part=id%2Creplies%2Csnippet&channelId=UCxz_B5DVTdZV5c0JLctjqUA&alt=json'
(Pdb) request.body
(Pdb) request.to_json()
'{"uri": "https://youtube.googleapis.com/youtube/v3/commentThreads?part=id%2Creplies%2Csnippet&channelId=UCxz_B5DVTdZV5c0JLctjqUA&alt=json", "method": "GET", "body": null, "headers": {"accept": "application/json", "accept-encoding": "gzip, deflate", "user-agent": "(gzip)", "x-goog-api-client": "gdcl/2.52.0 gl-python/3.8.10", "content-length": "0"}, "methodId": "youtube.commentThreads.list", "resumable": null, "response_callbacks": [], "_in_error_state": false, "body_size": 0, "resumable_uri": null, "resumable_progress": 0}'
(Pdb) request.body
On the other hand lines below return a valid 200 response.
(Pdb) request=self.service.commentThreads().list(part="id,replies,snippet", allThreadsRelatedToChannelId="UCxz_B5DVTdZV5c0JLctjqUA")
INFO __init__.py line:49 2022-09-19 22:06:17,504 - file_cache is only supported with oauth2client<4.0.0
(Pdb) request.execute()
I have enabled Youtube Data API and give youtube.force-ssl scope again on Google Cloud console but I am not sure that am I have to give any other permissions. According to the doc. channelId should be a valid argument but I didn't understand why it returns 400 error if I gave channelId.
Weirdest thing is that even the same example on Google's documentation does not work.
However if I give my channel's id with allThreadsRelatedToChannelId argument it returns a HTTP 200 responseas expected.
They had removed channelId parameter :( https://issuetracker.google.com/issues/247966553
From linkedIn's own documented example here
https://learn.microsoft.com/en-us/linkedin/marketing/integrations/ads/account-structure/create-and-manage-campaigns?view=li-lms-2022-07&tabs=http#search-for-campaigns
Request headers:
Authorization: 'Bearer <redacted>',
'X-Restli-Protocol-Version': '2.0.0',
'Linkedin-Version': '202206',
Request Url:
GET https://api.linkedin.com/rest/adCampaigns?q=search&search.type.values[0]=SPONSORED_UPDATES&search.status.values[0]=ACTIVE&sort.field=ID&sort.order=DESCENDING
Returns:
HTTP code 403 with this error:
data: {
serviceErrorCode: 100,
code: 'ACCESS_DENIED',
message: 'Unpermitted fields present in PARAMETER: Data Processing Exception while processing fields [/search.status.values[0], /sort.field, /sort.order]'
}
I am confident my access token is ok as the request works using protocol v1.0.
app has the following permissions
r_organization_social
rw_organization_admin
r_1st_connections_size
r_organization_admin
r_ads_reporting r_emailaddress r_liteprofile
r_basicprofile
r_ads
rw_ads
w_member_social
w_organization_social
I had to REMOVE the Restli header, then it worked:
'X-Restli-Protocol-Version': '2.0.0'
I am attempting to retrieve an access token using my refresh token, client id and client secret for the youtube api using R Code.
This is google's example of how to POST a request.
POST /o/oauth2/token HTTP/1.1 Host: accounts.google.com Content-Type: application/x-www-form-urlencoded client_id=21302922996.apps.googleusercontent.com&client_secret=XTHhXh1SlUNgvyWGwDk1EjXB&refresh_token=1/6BMfW9j53gdGImsixUH6kU5RsR4zwI9lUVX-tqf8JXQ&grant_type=refresh_token
This was my r code:
library(httr)
url<- paste("https://accounts.google.com/o/oauth2/token?client_id=", client_id, "&client_secret=", client_secret, "&refresh_token=", refresh_token, "&grant_type=access_token", sep="")
POST(url)
And I keep getting this response:
Response [https://accounts.google.com/o/oauth2/token?client_id=xxxxxxxxxx&client_secret=xxxxxxxx&refresh_token=xxxxxxxxxxxxxxxxxxxxxx&grant_type=refresh_token]
Date: 2015-09-02 16:43
Status: 400
Content-Type: application/json
Size: 102 B
{
"error" : "invalid_request",
"error_description" : "Required parameter is missing: grant_type"
Is there a better way to do this? Maybe using RCurl? If so, what would the format of the request be? I would appreciate help on this!
The RAdwords package has a function to retrieve the refresh token. If you don't want to add the entire package you can just add the following code to your script.
refreshToken = function(google_auth) {
# This function refreshes the access token.
# The access token deprecates after one hour and has to updated
# with the refresh token.
#
# Args:
# access.token$refreh_token and credentials as input
# Returns:
# New access.token with corresponding time stamp
rt = rjson::fromJSON(RCurl::postForm('https://accounts.google.com/o/oauth2/token',
refresh_token=google_auth$access$refresh_token,
client_id=google_auth$credentials$c.id,
client_secret=google_auth$credentials$c.secret,
grant_type="refresh_token",
style="POST",
.opts = list(ssl.verifypeer = FALSE)))
access <- rt
access
}
I am trying to generate a POST request for the requests endpoint in the following python code:
import requests
...
response = requests.post(
'https://sandbox-api.uber.com/v1/requests',
headers = {
'Authorization': 'Bearer %s' % access_token,
'Content-Type': 'application/json'
},
params={"start_latitude":"37.334381","start_longitude":"-121.89432","end_latitude":"37.77703","end_longitude":"-122.419571","product_id":"a1111c8c-c720-46c3-8534-2fcdd730040d"})
data = response.json()
The access_token was obtained using request scope during authorization. The response json is :
{"message": "Unable to parse JSON in request body.", "code": "invalid_json"}
Need help in formatting the request properly. Thanks.
Figured out the problem - had to replace the params field with a data field and wrap the dict with json.dumps() before sending it off.