RestAssured - how to send a request without Content-Type? - rest-assured

I am using RestAssured to send a request:
Map<String, Object> headers = new HashMap<>();
headers.put("Accept", "*/*");
headers.put("Accept-Encoding", "gzip, deflate, br");
headers.put("Connection", "keep-alive");
Response response = RestAssured.given().baseUri(BASE_URL)
.headers(headers)
.log().all()
.post(URL_PREFIX + "/documents/request/" + username);
However, in the log I see that 1 more header was automatically added:
Content-Type=application/x-www-form-urlencoded; charset=ISO-8859-1
And I get 415 error.
Is it possible to send a request without Content-Type? I mean, without this header at all; if the request is sent with Content-Type equal to empty line, there is still a 400 error; the only way to make it work is to send the request without this header.

Seems like there is a bug in the RestAssured framework that is still open (I verified that in 4.3.3).
// https://mvnrepository.com/artifact/io.rest-assured/rest-assured
testImplementation group: 'io.rest-assured', name: 'rest-assured', version: '4.3.3'
Founded out, when creating negative tests for a API. Content type below is automatically generated when trying to send request.
Content-Type=application/x-www-form-urlencoded; charset=ISO-8859-1
Bug defined here:
https://github.com/rest-assured/rest-assured/issues/656
https://github.com/rest-assured/rest-assured/issues/986

Related

How do I add a file into a HTTP PUT request calling the Microsoft Graph API?

I am trying to upload a file to a SharePoint Drive by using Microsoft Graph. I am new to REST APIs and Microsoft Graph.
This is what the documentation says:
PUT /me/drive/root:/FolderA/FileB.txt:/content
Content-Type: text/plain
The contents of the file goes here.
Before all of this, I do have my authorization/bearer token and I am able to call the HTTP get but I am not able to upload the file using HTTP PPU.
URL url = new URL(newUrl);
String readLine;
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization","Bearer "+ token);
connection.setRequestProperty("Accept","application/json");
This returns java.io.IOException: Server returned HTTP response code: 411 for URL.
I have tried passing it as a binary stream but the request is still failing.
The "type" of the file is determined by the Content-Type header. For some context, the Accept header states the format you expect the response body to use while the Content-Type states the format of your request.
To upload a standard text file, you'll want to use Content-Type: text/plain:
URL url = new URL(newUrl);
String readLine;
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization","Bearer "+ token);
connection.setRequestProperty("Accept","application/json");
connection.setRequestProperty("Content-Type","text/plain");

Swagger OpenAPI post application/json without requestbody

My API consumes requests only with Header - Content-type:application/json object.
To do the same I use:
#OA\RequestBody(
description= "Provide company search parameter",
required= true,
#OA\JsonContent(
type="object",
#OA\Property(property="company_name", type="string")
)
)
But for some requests I don't need the RequestBody, only hit the resource and get data. How do I do it without RequestBody?
P.S. This request requires a GET method (POST can be used, if that helps) but GET doesn't accept a RequestBody.
This case cannot be described by OAS 3.0, and the restriction on GET requestBodies is to avoid attempting to describe API behaviour which the HTTP spec says is undefined. The restriction on specifying Content-Type as a 'manually' defined header is also to ensure there is no ambiguity as to which mechanism is supposed to set this header.
https://github.com/OAI/OpenAPI-Specification/issues/1628
When a client is sending the Content-Type header, it is used to describe the body of the request (not the response)
To influence the the response type a client can send an Accept header.
For example: Accept: application/json

BigCommerce oAuth auth token request always returning 401

I can not figure out what I'm doing wrong. I'm developing an App for BigCommerce and can not get the simple oAuth exchange to work correctly.
The initial get request is being made to https://www.my-app.com/oauth/bigcommerce/auth. This is the code in the controller for that request. It's a Laravel 5.6 app:
use Illuminate\Http\Request;
use Bigcommerce\Api\Client as Bigcommerce;
class BigcommerceOAuthController extends Controller
{
public function auth(Request $request)
{
$object = new \stdClass();
$object->client_id = 'my-client-id';
$object->client_secret = 'my-client-secret';
$object->redirect_uri = 'https://my-app.com/oauth/bigcommerce/auth';
$object->code = $request->get('code');
$object->context = $request->get('context');
$object->scope = $request->get('scope');
$authTokenResponse = Bigcommerce::getAuthToken($object);
$storeHash = str_replace('stores/', '', $request->get('context'));
Bigcommerce::configure(array(
'client_id' => 'my-client-id',
'auth_token' => $authTokenResponse->access_token,
'store_hash' => $storeHash
));
echo "<pre>";
print_r($authTokenResponse);
print_r(Bigcommerce::getTime());
echo "</pre>";
}
}
Every time I try to install my draft app from the BigCommerce control panel, I get an error because $authTokenResponse is not an object. When I debug further into the Bigcommerce\Api\Connection class, I can see that the response from the server is empty, and the status is a 401, which means "Unauthorized".
I can't figure out why I am getting this error. As far as I can see, I'm doing everything right. I've tried urlencoding the string retrieved from $request->get('scope'), since that string becomes unencoded by Laravel, but that didn't seem to help.
I am also confused how this is even supposed to work at all. In the BigCommerce docs, they show this example POST request, which uses application/x-www-form-urlencoded Content-Type and passes the request body as a url encoded string:
POST /oauth2/token HTTP/1.1 Host: login.bigcommerce.com Content-Type:
application/x-www-form-urlencoded Content-Length: 186
client_id={CLIENT_ID}&client_secret={CLIENT_SECRET}&code=qr6h3thvbvag2ffq&scope=store_v2_orders&grant_type=authorization_code&redirect_uri=https://app.example.com/oauth&context=stores/{STORE_HASH}
However, if you inspect what's going on in the Connection class, you can see that the Content-Type is being set to application/x-www-form-urlencoded as the docs say, but the request body is being passed in as a json string, not a url string. Shouldn't the request be a url encoded string as the docs suggest?
A couple of things here to check:
Do you have a public URL where you can receive the Auth Callback?
If so, did the store owner registered the app successfully? https://developer.bigcommerce.com/api/registration
When you have the client_id and secret_id. You should have all of the details needed to send a POST request to the BC Auth Token Service at https://login.bigcommerce.com/oauth2/token
The content uses URL encode Make sure to URL encode your content. Be careful of of the encoding of & and = signs when those are actually being used as separators.
More details can be found in this post:
Can BigCommerce Private Apps use OAuth

Error 401 Unauthorized MVC .NET WEB APP

I am working with an API that wants me to send the token along with Header, specifically Content Header.
Here is my code block.
string path_current_user = "me";
var cookie = HttpContext.Request.Cookies.Get("cookietoken");
string cookie_with_token = "ACCESS_TOKEN="+cookie.Value+";";
client.DefaultRequestHeaders.Add("Cookie", cookie_with_token);
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
HttpResponseMessage response = await client.GetAsync(path_current_user);
I always get a 410 Unauthorized response. However, during debugging I can collect the values from the client object, and copy paste them into https://www.hurl.it, and I get the expected 200 OK response. So, I know the values that are being stored in the above code are correct. Its not a credentials issue for sure.
I have looked at almost 50 different threads on stack overflow, but none of them talk about this specification situation. Doing a GET with the Header Content set. Here is a screenshot of the HURL that works just fine.
Update 1 - Here is the API documentation for what I am trying to achieve.
Endpoint
GET me
Request Route
GET me
Headers
Content-Type: application/json Cookie: ACCESS_TOKEN="token characters
come here and remove the quotes"; Host: x.x
Update 2 - One of my mentors, recommended the following.
using (var httpClient = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Get, "https://small-project-api.herokuapp.com/me");
request.Headers.Add.("Content-Type", "application/json");
request.Headers.Add.("Cookie", cookie_with_token);
var response2 = await httpClient.SendAsync(request);
var responsestring = await response2.Content.ReadAsStringAsync();
}
He is of the opinion that may be such a request, as mentioned below, simply won't work in dot net. I am all but ready to give up here.

Odata Put JSON Request Body Error

I am trying to create a PUT request using Fiddler but I am constantly receiving an error as follows.
PUT Request
https://127.0.0.1/odata/ControllerName('param')
Request Header
Accept: application/json;odata=minimalmetadata
Host: 127.0.0.1
Authorization: ApiKey uniqueKey
Content-Type: application/json;odata=minimalmetadata
Accept-Charset: UTF-8
RequestBody
{"Name":"param"}
When I am trying to PUT, it returns me status code 400. When I double click error in fiddler and view JSON tab, it gives me following error.
odata.error
innererror
message=actionParameters : The last segment of the request URI 'ControllerName('param')' was not recognized as an OData action.
Where I am going wrong, with URI format or request body?
According to OData protocol,
the value within the parenthesis following the entity set(corresponds to a controller) must be a key, for example:
~/odata/Products(1) if the key is of int type,
~/odata/Products('1') if the key is of string type.
So please make sure the key is of string type in your case, and try to
GET https://127.0.0.1/odata/ControllerName('param')
to see whether the response is as expected.

Resources