Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
i'm looking for a tool or library that allow me to quickly develop a Spring Boot backend that expose mocked REST services while we're waiting to have specifications about services business logic from our customer.
Are there any best practices? For example reading from JSON files or something else?
Thanks to all
*********************** Additional infos ***********************
I want use same server (embedded one) because some API's are already developed.
I need a real service response, not test one.
I would like to have something more structured than return statement
return "{
\"id\": 01,
\"name\": \"Donald Stumpet\"
}";
Wiremock will be your buddy in this case (http://wiremock.org/docs/getting-started/)
In your spring boot test class, setup wiremock rule:
#Value("${wireMockServer.port}")
private int wireMockPort;
private WireMockRule wireMockRule;
#Rule
public WireMockRule getWireMockRule() {
if (wireMockRule == null) {
wireMockRule = new WireMockRule(wireMockConfig().port(wireMockPort).notifier(new Slf4jNotifier(true)));
}
return wireMockRule;
}
And then just mock your API:
String url = UriComponentsBuilder
.fromUriString("XXXXX").buildAndExpand("pathParam1", "pathParamVal").toUriString();
stubFor(get(urlEqualTo(url))
.willReturn(aResponse()
.withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
.withHeader("Connection", "close")
.withBody(asJson(mockedResponseObject))));
If you want not to programmatically stub your requests and store them in json files , then
mention the mappings location with the property wireMock.mappingsUnderClasspath
And inside that directory, create a folder called mappings and put your mapping json files:
eg.
{
"request": {
"method": "GET",
"urlPattern": "/foo/myApi"
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/json"
},
"bodyFileName": "mockedResponse.json"
}
}
And keep the mockedResponse.json in a directory called __files (double underscore) inside wireMock.mappingsUnderClasspath
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 13 days ago.
Improve this question
process.env.variable is working in local development but after deploying to Heroku its not working again. I use nuxt.js
The value shows as undefined:
https://prnt.sc/l1GMK6xAQP-V
The config var is correct. I restarted the app. still nothing.
Got it!
.env file:
BASE_URL=http://localhost:3000
ORIGIN_HEADER=localhost
nuxt.config.js
export default {
publicRuntimeConfig: {
baseUrl: process.env.BASE_URL,
originHeader: process.env.ORIGIN_HEADER
}
}
.vue component:
<template>
<div>
<p>Base URL: {{ baseUrl }}</p>
<p>Origin Header: {{ originHeader }}</p>
</div>
</template>
<script>
export default {
computed: {
baseUrl() {
return this.$config.baseUrl
},
originHeader() {
return this.$config.originHeader
}
}
}
</script>
publicRuntimeConfig is intended to be used for configuration values that are safe to be publicly exposed, such as API endpoints or public-facing URLs.
privateRuntimeConfig, on the other hand, is intended for configuration values that should be kept private and should not be publicly exposed, such as API keys or secrets.
I would like to map this rest interface in OpenApi?
Is there by chance a tool with which I can create an OpenApi from the rest interface without including this tool in my Spring Boot Application? Or is there a template I can use to build the interface myself in Openapi? I would be very grateful for an approach.
#GetMapping("/page")
public Page<FootballTeamLocationEntityView> getPageableFootballTeamList(#PageableDefault(value = 10) Pageable pageable) {
return footballTeamService.getFootballTeams(pageable);
}
I use OpenApi 3.0 and Spring Boot 2
UPDATE 1
default ResponseEntity<FootballTeamLocation> getPageableFootballTeamList(Pageable pageable) {
getRequest().ifPresent(request -> {
for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) {
if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) {
String exampleString = "{ \"name\" : \"Westfalen-Stadion\", \"locZ\" : 5.962133212312, \"externalId\" : \"externalId\", \"locX\" : 6.02749381870403, \"id\" : 0, \"locY\" : 11.4658129805029452 }";
ApiUtil.setExampleResponse(request, "application/json", exampleString);
break;
}
}
});
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
Consider using springdoc. It is a recent library that is easier to use and way less error-prone than Springfox (the other option for Spring Boot apps). We moved to it 2 years ago and we are very glad we did. There is very good documentation and tutorials online for it:
https://springdoc.org/
https://www.baeldung.com/spring-rest-openapi-documentation
It is also very active and you usually get your issues answered very fast on the github page.
We are using token-based authentication (with Spring Security) in our Spring Boot 2 application. Now I'm introducing Spring Boot Actuator to it. I would like to configure the /health endpoint to be visible without any permissions but to show health checks details only when authorized.
I found the property management.endpoint.health.show-details=when_authorized which should be helpful but now I'm fighting with the Spring Security configuration to allow everybody to see:
{
"status": "UP"
}
under /actuator/health while users authorized with token should see:
{
"status": "UP",
"details": { ... }
}
Did you face a similar problem? How did you handle it?
OK, now I understand, if you turn off security in your application and keep management.endpoint.health.show-details=when_authorized you are getting just status field? If I'm right it's not an issue, take a look in spring class HealthWebEndpointResponseMapper into map method. As I found out this method overwrites (remove details field from the response) if condition in if is true:
public WebEndpointResponse<Health> map(Health health, SecurityContext securityContext,
ShowDetails showDetails) {
if (showDetails == ShowDetails.NEVER
|| (showDetails == ShowDetails.WHEN_AUTHORIZED
&& (securityContext.getPrincipal() == null
|| !isUserInRole(securityContext)))) {
health = Health.status(health.getStatus()).build();
}
Integer status = this.statusHttpMapper.mapStatus(health.getStatus());
return new WebEndpointResponse<>(health, status);
}
In your case, I guess you have set an above-mentioned property to when_authorized also you have turned off authentication, so the principal is null. Not sure if I'm right, but I hope I gave you a clue. :)
The service is consuming google maps api (geocode).
When I execute a GET using default bean configuration for spring resttemplate, I have a value different from when I execute this GET on web browser (Chrome).
Call on Chrome and using resttemplate:
https://maps.googleapis.com/maps/api/geocode/json?key=mykeymykeymykeymykey&address=Rua%20Marques%20de%20Valenca,%20100,%20Alto%20da%20Mooca,%20S%C3%A3o%20Paulo%20-%20SP,%20Brasil&language=pt-BR
When I execute a reverse geocode, the chrome execution is more precise.
Results:
Chrome:
location: {
lat: -23.5577251,
lng: -46.5948733
},
RestTemplate:
location: {
lat: -23.5574375,
lng: -46.5948733
},
I´ve tried use Double, Float and BigDecimal. And I try create a deserializer to get this value before the serialization, but the value is the same.
I´m using Java 8 with Spring Boot 2.0.3.
Anyone knows how to accurate it?
I was using UriComponentsBuilder and when I use toUriString the url was formatted to browser and it was not working correctly.
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(googleHost)
.queryParam("key", apiKey)
.queryParam(input, address)
.queryParam("language", language);
It´s working now using StringUtils.join(...) to build the URI.
String googleurl = StringUtils.join(googleGeocodingHost,
"?key=", apiKey, "&", input, "=", address, "&language=", language);
We have a asp.net web api application which uses swagger/swashbuckle for it's api documentation. The api is secured by azure AD using oauth/openid-connect. The configuration for swagger is done in code:
var oauthParams = new Dictionary<string, string>
{
{ "resource", "https://blahblahblah/someId" }
};
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.SingleApiVersion(Version, Name);
c.UseFullTypeNameInSchemaIds();
c.OAuth2("oauth2")
.Description("OAuth2 Implicit Grant")
.Flow("implicit")
.AuthorizationUrl(
"https://login.microsoftonline.com/te/ourtenant/ourcustompolicy/oauth2/authorize")
.TokenUrl(
"https://login.microsoftonline.com/te/ourtenant/ourcustompolicy/oauth2/token");
c.OperationFilter<AssignOAuth2SecurityRequirements>();
})
.EnableSwaggerUi(c =>
{
c.EnableOAuth2Support(_applicationId, null, "http://localhost:49919/swagger/ui/o2c-html", "Swagger", " ", oauthParams);
c.BooleanValues(new[] { "0", "1" });
c.DisableValidator();
c.DocExpansion(DocExpansion.List);
});
When swashbuckle constructs the auth url for login, it automatically adds:
&scope=
However I need this to be:
&scope=openid
I have tried adding this:
var oauthParams = new Dictionary<string, string>
{
{ "resource", "https://blahblahblah/someId" },
{ "scope", "openid" }
};
But this then adds:
&scope=&someotherparam=someothervalue&scope=openid
Any ideas how to add
&scope=openid
To the auth url that swashbuckle constructs?
Many thanks
So, found out what the issue was, the offending code can be found here:
https://github.com/swagger-api/swagger-ui/blob/2.x/dist/lib/swagger-oauth.js
These js files are from a git submodule that references the old version of the UI.
I can see on lines 154-158 we have this code:
url += '&redirect_uri=' + encodeURIComponent(redirectUrl);
url += '&realm=' + encodeURIComponent(realm);
url += '&client_id=' + encodeURIComponent(clientId);
url += '&scope=' + encodeURIComponent(scopes.join(scopeSeparator));
url += '&state=' + encodeURIComponent(state);
It basically adds scopes regardless of whether there are scopes or not. This means you cannot add scopes in the additionalQueryParams dictionary that gets sent into EnableOAuth2Support as you will get a url that contains 2 scope query params i.e.
&scope=&otherparam=otherparamvalue&scope=openid
A simple length check around the scopes would fix it.
I ended up removing swashbuckle from the web api project and added a different nuget package called swagger-net, found here:
https://www.nuget.org/packages/Swagger-Net/
This is actively maintained and it resolved the issue and uses a newer version of the swagger ui. The configuration remained exactly the same, the only thing you need to change is your reply url which is now:
http://your-url/swagger/ui/oauth2-redirect-html