Elixir Phoenix problem with phx.gen.json command - phoenix-framework

I'm trying to create a project but I'm unable to create objects via the API, I'm using only commands to create the Phoenix project and it still doesn't work.
Steps to reproduce:
I'm using the following commands
mix phx.new project --app project --module TodoList --no-html --no-webpack
cd project
mix ecto.create
mix phx.gen.json Accounts User users first_name:string last_name:string
Then I add the resource in my router.ex file like so:
scope "/api", TodoListWeb do
pipe_through :api
resources "/users", UserController
end
And finnally:
mix ecto.migrate
mix phx.server
After that the server start without any issues, up to this point everything is fine, but when I do a POST request on http://localhost:4000/api/users using Postman, with any parameters I get a 400 status code.
With the following message:
I can see in the console the intput of the request:
%{"first_name" => "Jeff", "last_name" => "Doe"}

I think you need to specify an outermost "user" key in the request, as in:
%{"user" => %{"first_name" => "Jeff", "last_name" => "Doe"}}
So your JSON request on Postman needs to be:
{
"user": {
"first_name": "Jeff",
"last_name": "Doe"
}
}

Related

google analytics GA4 API integration in RAILS 5.2 using google-apis-analyticsdata_v1beta gem library

I'm getting an error in request invalid
`gem 'google-apis-analyticsdata_v1beta', '~> 0.21.0'
# Load the client
require "google/apis/analyticsdata_v1beta"
require 'googleauth'
namespace :google_analytics do
desc 'cron job for syncing google analytics services'
task :analytics => [:environment] do
begin
client = Google::Apis::AnalyticsdataV1beta::AnalyticsDataService.new
credentials = Google::Auth::ServiceAccountCredentials.make_creds(json_key_io: IO.new(IO.sysopen('credentials.json')))
credentials.scope = 'https://www.googleapis.com/auth/analytics.readonly'
client.authorization = credentials.fetch_access_token!({})["access_token"]
body = {
"requests": [
{
"date_ranges": [
{
"start_date": "7daysAgo",
"end_date": "today"
}
],
"dimensions": [
{
"name": "pageTitle"
}
]
}
]
}
request = Google::Apis::AnalyticsdataV1beta::BatchRunReportsRequest.new(body)
property_id = '3384098947333'
property = "properties/#{property_id}"
results = client.batch_property_run_reports(property, request)
pp results
rescue => exception
puts "Exception : Error"
puts exception.message
puts "------------------------------"
end
end
end
i have tried gem 'google-apis-analyticsdata_v1beta' which help us to send API along with authorisation
I have created custom user field with custom event so i can get that data back for showing report in my so using API for the same but getting error in request, what exactly syntax for the same not sure, lack of documentation won't be able to do it well, if anyone help that would be great
creating job so that will run every periodically and fetch data to my app from google analytics

Use Laravel Socialite user returns missing authorization_code

I'm using Laravel Socialite to login with SuperOffice API. Have only just added the provider as a pr but testing it already. I'm using the provider superoffice locally and inside a package superoffice-api I'm creating. Have added both packages to composer.json in the Laravel app:
"repositories": [
{
"type": "path",
"url": "./packages/superoffice-api"
},
{
"type": "path",
"url": "./packages/superoffice"
}
]
Also added the superoffice Socialite provider in the superoffice-api composer.json in the same way.
The login process is working but the problem starts when trying to use the user for other API calls. What I mean with this is on the callback I can do the following:
public function superofficeCallback(Request $request): RedirectResponse
{
$user = Socialite::driver('superoffice')->stateless()->user();
return redirect()->route('dashboard.index')->with([
'message' => 'Loggedin with SuperOffice as '.$user->name,
'success' => true,
]);
}
This shows the $user->name as expected. Now when trying to call Socialite::driver('superoffice')->stateless()->user() in the superoffice-api package I get the following error message:
GuzzleHttp\Exception\ClientException: Client error: POST https://sod.superoffice.com/login/common/oauth/tokens resulted in a 400 Bad Request response:
{ "error": "invalid_request", "error_description": "missing authorization_code"}
It doesn't matter if called in a method or in the __construct() of a class.
So my question is how can I use a Socialite provider superoffice user in a package superoffice-api? This is needed to get the access_token. Can imagine that because Socialite is called in a package some sort of reference is missing.
The problem here is that the access_token and refresh_token need to be stored in some other way in the callback function. When stored for example in the database you're able to use the tokens anywhere.

Vercel/NextJS: How to access serverless functions from frontend during local development?

My React/NextJS front end has a Button component that fetches data via a serverless function when the button is clicked. I want to test this functionality during local development with the Vercel dev/CLI tools. I am getting a 404 result when attempting to access my lambda functions. Here are the approximate steps that I've gone through so far:
Create package.json with a dev script:
...
"scripts": {
"dev": "yarn codegen && next --hostname=0.0.0.0 --port=3001",
}
...
Link to deployed vercel project
Create vercel.json to specify builds and routes:
...
"builds": [
{ "src": "*.html", "use": "#now/static" },
{ "src": "pages/api/*.py", "use": "#now/python" },
],
"routes": [
{ "src": "/api/validate", "dest": "/pages/api/validate.py" }
]
...
Create my test Lambda function (in python):
from http.server import BaseHTTPRequestHandler
from datetime import datetime
class handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write(str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')).encode())
return
Create my Button component:
...
<Button
variant="contained"
color="secondary"
onClick={() => {
fetch('api/validate')
.then(response => { console.log(response)
response.json() })
.then(data => console.log(data))
}}
>
Generate sample dataset
</Button>
...
Run vercel dev
Access website at localhost:3001 (next dev server address)
Click button
Result:
I'm receiving a 404 response
Note: I can access the lambda function from localhost:3000/pages/api/validate.py (vercel dev server address). This appears to manually kickstart the lambda function build and serve process. I thought that it should have been built and served already from the vercel.json specification and be available at localhost:3001/api/validate. This seems to agree with the Vercel documentation.
Note 2: Next dev/CLI tools build and serve javascript/typescript files just fine. I'm using python and Go functions as well, which are supported by Vercel dev/CLI but not Next
My solution was to use vercel dev instead of next dev or yarn dev, and to use an environment variable in a .env file that points to the function url. This env variable should be prepended with NEXT_PUBLIC_ so that it is registered by next.js and passed to process.env during the build process.
# .env
NEXT_PUBLIC_FUNCTIONS_BASE_URL="http://localhost:3000" # 3000 is vercel port
# component.js
...
fetch(process.env.NEXT_PUBLIC_FUNCTIONS_BASE_URL + '/api/function-name')
...
You need to pass the port from vercel dev to the upstream CLI, in this case next dev.
{
"scripts": {
"dev": "yarn codegen && next dev --port=$PORT",
}
}
Now when you run vercel dev, the ephemeral port will be proxied from the dev server.
You can also remove vercel.json if you rename /pages/api to /api.

How to set a base url in a springboot graphql app

How can we set a base url in springboot graphql-server app .
By default the graphiql api-console opens on http://localhost:8080/graphiql
Trying to access http://localhost:8080 through postman with a post -query as below :
{
bookings {
name
}
}
gives an error saying :
{
"timestamp": 1549913598497,
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/"
}
Q1 what should be the path to the server i should be using to invoke it.
Q2 is there a way to provide a custom base path something loke http://localhost:8080/service/api/query
Usually the server path for graphql endpoints is at http://localhost:8080/graphql. If not just inspect the network tab on your browser when you run a query on your GraphiQL interface, it will run the query on the api endpoint.
In order to change the base path you would need to change application.properties into something like:
graphql.servlet.mapping: /service/api/query
graphiql.mapping: /graphiql
graphiql.endpoint: /service/api/query
If you are using Spring Boot Property file you can change the base url like below:
spring.graphql.path=/service/api/query
Example:
When I changed the base url like below.:
spring.graphql.path=/api/projects/graphql
It reflected like below in console:
2022-11-05 08:58:14.964 INFO 17336 --- [ main] s.b.a.g.s.GraphQlWebMvcAutoConfiguration : GraphQL endpoint HTTP POST /api/projects/graphql
More can be found at below official document:
https://docs.spring.io/spring-boot/docs/current/reference/html/application-properties.html#appendix.application-properties.web

Grails 3 - Spring Rest Docs using Rest assured giving SnippetException when using JSON views

I am trying to integrate Spring REST docs with rest assured with Grails 3.1.4 application. I am using JSON Views.
Complete code is at https://github.com/rohitpal99/rest-docs
In NoteController when I use
List<Note> noteList = Note.findAll()
Map response = [totalCount: noteList.size(), type: "note"]
render response as grails.converters.JSON
Document generation works well.
But I want to use JSON views like
respond Note.findAll()
where I have _notes.gson and index.gson files in /views directory. I get a SnippetException. A usual /notes GET request response is correct.
rest.docs.ApiDocumentationSpec > test and document get request for /index FAILED
org.springframework.restdocs.snippet.SnippetException at ApiDocumentationSpec.groovy:54
with no message. Unable to track why it occurs.
Please suggest.
Full stacktrace
org.springframework.restdocs.snippet.SnippetException: The following parts of the payload were not documented:
{
"instanceList" : [ {
"title" : "Hello, World!",
"body" : "Integration Test from Hello"
}, {
"title" : "Hello, Grails",
"body" : "Integration Test from Grails"
} ]
}
at org.springframework.restdocs.payload.AbstractFieldsSnippet.validateFieldDocumentation(AbstractFieldsSnippet.java:134)
at org.springframework.restdocs.payload.AbstractFieldsSnippet.createModel(AbstractFieldsSnippet.java:74)
at org.springframework.restdocs.snippet.TemplatedSnippet.document(TemplatedSnippet.java:64)
at org.springframework.restdocs.generate.RestDocumentationGenerator.handle(RestDocumentationGenerator.java:192)
at org.springframework.restdocs.restassured.RestDocumentationFilter.filter(RestDocumentationFilter.java:63)
at com.jayway.restassured.internal.filter.FilterContextImpl.next(FilterContextImpl.groovy:73)
at org.springframework.restdocs.restassured.RestAssuredRestDocumentationConfigurer.filter(RestAssuredRestDocumentationConfigurer.java:65)
at com.jayway.restassured.internal.filter.FilterContextImpl.next(FilterContextImpl.groovy:73)
at com.jayway.restassured.internal.RequestSpecificationImpl.applyPathParamsAndSendRequest(RequestSpecificationImpl.groovy:1574)
at com.jayway.restassured.internal.RequestSpecificationImpl.get(RequestSpecificationImpl.groovy:159)
at rest.docs.ApiDocumentationSpec.$tt__$spock_feature_0_0(ApiDocumentationSpec.groovy:54)
at rest.docs.ApiDocumentationSpec.test and document get request for /index_closure2(ApiDocumentationSpec.groovy)
at groovy.lang.Closure.call(Closure.java:426)
at groovy.lang.Closure.call(Closure.java:442)
at grails.transaction.GrailsTransactionTemplate$1.doInTransaction(GrailsTransactionTemplate.groovy:70)
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:133)
at grails.transaction.GrailsTransactionTemplate.executeAndRollback(GrailsTransactionTemplate.groovy:67)
at rest.docs.ApiDocumentationSpec.test and document get request for /index(ApiDocumentationSpec.groovy)
REST Docs will fail a test if you try to document something that isn't there or fail to document something that is there. You've documented two fields in your test:
responseFields(
fieldWithPath('totalCount').description('Total count'),
fieldWithPath('type').description("Type of result")
)))
REST Docs has failed the test as some parts of the response haven't been documented. Specifically an instanceList array that contains maps with two keys: title and body. You can document those and the other two fields with something like this:
responseFields(
fieldWithPath('totalCount').description('Total count'),
fieldWithPath('type').description("Type of result"),
fieldWithPath('instanceList[].title').description('Foo'),
fieldWithPath('instanceList[].body').description('Bar')
)))
If you don't care about potentially missing fields, you can use relaxedResponseFields instead of responseFields:
relaxedResponseFields(
fieldWithPath('totalCount').description('Total count'),
fieldWithPath('type').description("Type of result")
))
This won't fail the test if some fields are not mentioned.

Resources