Spring Boot WebClient Sending Basic GraphQL POST Request As a Raw String - spring-boot

I'm trying to get even a basic query to send to my graphql server using WebClient, I have the following:
String query = "{ query: 'query testQuery { testData }' }";
String response = WebClient.builder().build().post().uri("http://localhost:4020/graphql")
.bodyValue(query).retrieve().bodyToMono(String.class).block();
This is always producing a 400 Bad Request from POST response.
On the sever side, however, I am not seeing anything in the request body, here is the debugging output from my node server (ApolloServer):
[1] headers: {
[1] 'accept-encoding': 'gzip',
[1] 'user-agent': 'ReactorNetty/1.0.20',
[1] host: 'localhost:4020',
[1] accept: '*/*',
[1] 'content-type': 'text/plain;charset=UTF-8',
[1] 'content-length': '49'
[1] }
[1] baseUrl: /graphql
[1] body: {}
I have tried a number of different combinations to get this to work, to no avail.
In order to ensure the API is functioning for this call, the following curl command works:
curl --request POST \
--header 'content-type: application/json' \
--url http://localhost:4020/graphql \
--data '{"query":"query testQuery { testData }" }'
[1] headers: {
[1] host: 'localhost:4020',
[1] 'user-agent': 'curl/7.79.1',
[1] accept: '*/*',
[1] 'content-type': 'application/json',
[1] 'content-length': '41'
[1] }
[1] baseUrl: /graphql
[1] body: { query: 'query testQuery { testData }' }
Edit
So this seems to be related to the this github issue, there are 2 things, 'application/json' is required and rawbytes must be used to send strings. The following code works:
String query = "{ \"query\": \"query testQuery { testData }\" }";
String response = WebClient.builder().build().post().uri("http://localhost:4020/graphql")
.contentType(MediaType.APPLICATION_JSON).bodyValue(query.getBytes()).retrieve()
.bodyToMono(String.class).block();

Related

How to do a simple GraphQL query in a native Ruby script

I'm trying to figure out how to do a simple GraphQL query without using gems. The following cURL commands works
curl -X POST "https://gql.example.com/graphql/public" \
-H "Authorization: Bearer <ACCESS_TOKEN>" \
-H "Content-Type: application/json" \
-d '{ "query": "query { user { id defaultEmail } }", "variables": {} }'
and the corresponding javascript code is
fetch('https://gql.example.com/graphql/public', {
method: 'POST',
headers: {
'Authorization': 'Bearer <ACCESS_TOKEN>',
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: 'query { user { id defaultEmail } }',
variables: {}
})
})
.then(r => r.json())
.then(data => console.log(data));
Is it possible to do this easily in Ruby without using the graphql gem? I only need to do simple queries like the examples above so I'm hoping it's easy to do them in a single Ruby script.
You can use Ruby core lib Net/HTTP and build your requests like so:
require 'net/http'
uri = URI('https://gql.example.com/graphql/public')
params = {'query': 'query { user { id defaultEmail } }', 'variables': {} }
headers = {
"Authorization'=>'Bearer #{ENV['MY_ACCESS_TOKEN']}",
'Content-Type' =>'application/json',
'Accept'=>'application/json'
}
https = Net::HTTPS.new(uri.host, uri.port)
response = https.post(uri.path, params.to_json, headers)
See this answer as well

RestClient post request in ruby on rails

RestClient post request
I tried post request couple ways
#user = {name: 'xxxxxx', email: 'xxxxxx#gmail.com', password: 'qwertyqqq'}
RestClient.post 'http://localhost:4123/api/users?token=<token>', #user
RestClient::Request.execute(method: :post, url: 'http://localhost:4123/api/v1/users', token: '<token>', payload: '#user', headers: {"Content-Type" => "application/json"})
Error: RestClient::BadRequest: 400 Bad Request or RestClient::UnprocessableEntity: 422 Unprocessable Entity
Success cases
When i made a get request with rest client and with curl is just fine.
RestClient.get 'http://localhost:4123/api/v1/users?token=<token>'
With curl:
Get request:
curl -X GET http://localhost:4123/api/v1/users/1?token=<token>
Post request for helpy:
curl -d '{"name":"xxxx","email":"xxxx#gmail.com","password":"12345678", "admin": true, "role":"admin"}' -H "Content-Type: application/json" -X POST http://localhost:4123/api/v1/users?token=<token>
The difference between the CURL version and the RestClient version is that in the CURL version you send a JSON string as payload but in the RestClient sends the string '#user'.
It should be fine when you actually send JSON:
RestClient.post(
"http://localhost:4123/api/v1/users?token=<token>",
#user.to_json,
{ content_type: :json, accept: :json }
)

Ruby RestClient GET request with payload

Please help me with the following:
I have a number of application and associated records.
app with id 1 has: record1, record2 and record3.
app with id 2 has: record1 ... record1000
To filter out records for app 1 Im using curl. I can get records with the following command:
curl -i -H "accept: application/json" -H "Content-type: application/json" -X GET -d '{ "filters": { "app_id":"1" }}' http://[rails_host]/v1/records?token=[api_token]
How can I do the same but with ruby RestClient (gem 'rest-client' '1.7.2')
To get all records I do the following:
RestClient.get("http://[rails_host]/v1/records?token=[api_token]", { :content_type => 'application/json', :accept => 'application/json'})
The Problem is that app ids are not returned so I cannot parse response and take records that has app id = 1
Any ideas how can I add payload to Restclient.get to filter out records?
You can see in the docs here that the only high level helpers that accept a payload argument are POST, PATCH, and PUT. To make a GET request using a payload you will need to use RestClient::Request.execute
This would look like:
RestClient::Request.execute(
method: :get,
url: "http://[rails_host]/v1/records?token=[api_token]",
payload: '{ "filters": { "app_id":"1" } }',
headers: { content_type: 'application/json', accept: 'application/json'}
)

Ruby rest-client returning 401 while curl command works

I have a working curl command which returns exactly what I want, bunch of JSON:
curl -D- -u username:password -X GET -H "Content-Type: application/json" https://stash.address.net/rest/api/1.0/projects/FOOBAR/repos\?limit\=1000
And I need to transform it into RestClient::Request, but I am still getting 401 back:
RestClient::Request.execute(
method: :get,
headers: {
content_type: 'application/json'
},
username: 'username',
password: 'password',
url: 'https://stash.address.net/rest/api/1.0/projects/FOOBAR/repos',
params: {
limit: '1000'
},
verify_ssl: false
)
Did I forget something? Is there something missing from my request? Isn't it exactly same as the curl command above?
From the documentation I don't see any mention of the username and params options. They suggest to interpolate the value in the URL.
RestClient.get 'https://username:password#stash.address.net/rest/api/1.0/projects/FOOBAR/repos', { accept: :json, params: { limit: 1000 }}

Having problems translating a curl command to Ruby Net::HTTP

This is a call to a Usergrid-stack web app to create a new application:
curl -H "Authorization: Bearer <auth_token>" \
-H "Content-Type: application/json" \
-X POST -d '{ "name":"myapp" }' \
http://<node ip>:8080/management/orgs/<org_name>/apps
Here's my Ruby code:
uri = URI.parse("http://#{server.ipv4_address}:8080/management/orgs/#{form.org_name}/apps")
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri, {'Authorization' => 'Bearer #{form.auth_token}', 'Content-Type' => 'application/json'})
request.set_form({"name" => form.app_name})
command.output.puts uri.request_uri
response = http.request(request)
Currently I'm getting this response from the server:
{\"error\":\"auth_unverified_oath\",\"timestamp\":1383613556291,\"duration\":0,\"exception\":\"org.usergrid.rest.exceptions.SecurityException\",\"error_description\":\"Unable to authenticate OAuth credentials\"}"
In this line--
request = Net::HTTP::Post.new(uri.request_uri, {'Authorization' => 'Bearer #{form.auth_token}', 'Content-Type' => 'application/json'})
Try changing that authorization string to "Bearer #{form.auth_token}"--with double quotes. String interpolation only works with double-quoted strings.

Resources