swagger parameter default is not in generated code.
for example:
paths:
/user/refresh.json:
post:
operationId: refresh
description: |
By passing in the appropriate options, you can search for
available inventory in the system
produces:
- application/json
consumes:
- application/x-www-form-urlencoded
parameters:
- name: "RC-App-Key"
in: "header"
description: appkey..
required: true
default: "abc"
type: "string"
the generated code like
public class DevelopersApiTest {
private final DevelopersApi api = new DevelopersApi();
#Test
public void refreshTest() throws ApiException {
String rcAppKey = null;
Common response = api.refresh(rcAppKey);
// TODO: test validations
}
the rcAppKey is null,but i want it be the default value "abc",like:
String rcAppKey = "abc";
Common response = api.refresh(rcAppKey);
the default value is not in generated code,but in .md file,how to put the default value into the code?
Related
The documentation for migrating to SpringDoc from Swagger2/SpringFox does not address how to convert response and responseContainer fields on #ApiOperation to the new #Operation annotation. How do I do this?
Before converting to SpringDoc, I was using response and responseContainer in SpringFox Swagger 2 to explicitly declare, for example, response="MyResponseDto.class" and responseContainer="List" in order to ensure that all MyResponseDto's properties and containing collection(s) were properly displayed in the Responses section of the documentation for each API call rather than just "string" or "object".
SpringDoc handles this all automatically and displays the responses correctly as long as I add the proper typing to the generic for ResponseEntity on my REST controller method signature.
So instead of this:
#GetMapping(value = "/items/{id}")
#Operation(summary = "Get items for component", description = "Retrieves all items for the component by the supplied id")
public ResponseEntity updateMapItem(#PathVariable String id) {
return new ResponseEntity<>(myService.getItemsForComponent(id), HttpStatus.OK);
}
Use this:
#GetMapping(value = "/items/{id}")
#Operation(summary = "Get items for component", description = "Retrieves all items for the component by the supplied id")
public ResponseEntity<List<MyResponseDto>> updateMapItem(#PathVariable String id) {
return new ResponseEntity<>(myService.getItemsForComponent(id), HttpStatus.OK);
}
Therefore, response="" and responseContainer="" are no longer necessary.
I'm adding Swagger UI 4 to existing Nest.js 7 project.
There was #Headers decorator for the Nest.js controller method argument.
I added #ApiBearerAuth nest.js decorator for method.
#ApiBearerAuth('MyAuth')
#Get()
async getEmployees(
#Headers('Authorization')
auth: string,
#Query() query: EmployeesQuery,
) {
The result is that I have Authorization header input field and lock icon button in Swagger UI at the same time. Lock icon button authorization works. Authorization header input field doesn't work and Swagger UI requires to fill it (input value is actually ignored by Nest.js).
How can I make Swagger authorization field to become not required and hidden?
Found how to make not required:
#ApiBearerAuth('MyAuth')
#ApiParam({
name: 'Authorization',
required: false,
description:
'(Leave empty. Use lock icon on the top-right to authorize)',
})
#Get()
async getEmployees(
#Headers('Authorization') auth: string,
#Query() query: EmployeesQuery,
) {
An alternative could be to use #Req() instead of #Headers().
#Get()
async getEmployees(
#Req() req: Request,
#Query() query: EmployeesQuery,
): Promise<Employees[]> {
const token = req.headers.authorization;
.
.
.
Note: import the type Request from express.
import { Request } from 'express';
You can also create a custom decorator.
It's better than the first answer because you don't have to pass the entire request for testing and actually hide the header in opposite to the second answer.
const AuthorizationToken = createParamDecorator(
(data: string, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();
return request.headers.authorization;
},
);
I am new to quarkus and have a bit familiar with swagger-ui. I am able to add a #Parameter to the an endpoint like this:
#Parameter(in = ParameterIn.HEADER, required = true, name = "my-header-id")
But, I would like to add this param to every endpoint. How can I achieve this?
I am using quarkus-smallrye-openapi for the ui.
You can specify parameters on method or class level. If you define the param as class field, then it will be added to all methods of the corresponding endpoint:
#Path("/someendpoint")
public class MyEndpoint {
#HeaderParam("my-header-id")
#Parameter(name = "my-header-id")
String myHeaderId;
#GET
public Response getAll() {return Response.ok().build()}
#GET
#Path("{id}")
public Response someMethod(#PathParam("id") String id) {return Response.ok().build();}
}
I'm having the following Azure Function which is HTTP triggered. I have set up Swagger for my endpoints using this link here. The following API expects a set of query string parameters, namely, "name", "email", "phone", so it can do some search against the target object. At the moment the body of the function of course is not implemented and that won't matter for this question though.
My question: How can I have the query string parameters displayed in the swagger UI?
The Function:
[FunctionName(nameof(GetBookingCalendarsFunction))]
public async Task<IActionResult> GetAllAsync(
[HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "bookings")] HttpRequest request,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
return new OkObjectResult($"Name: {request.Query["name"]}, email: {request.Query["email"]}, phone: {request.Query["phone"]}");
}
The swagger UI for this function
Note: I don't want to use route values instead of query string parameters, because, having those parameters are optional and the callers may not want to for example provide one of them.
For example, I've tried the following but it will fail with 404 if you remove any of the parameters as it takes them as part of the route (even though it will show them up in the Swagger)
[FunctionName(nameof(GetBookingCalendarsFunction))]
public async Task<IActionResult> GetAllAsync(
[HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "bookings/name={name}&email={email}&phone={phone}")] HttpRequest request,
string name, string email, string phone,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
return new OkObjectResult($"Name: {request.Query["name"]}, email: {request.Query["email"]}, phone: {request.Query["phone"]}");
}
I've been Googling around for hours now but couldn't find anything helpful so far. Appreciate your help.
Since you use package AzureExtensions.Swashbuckle to integrate Swagger in Azure function, we can use Attribute QueryStringParameter to configure query string according to your need. For more details, please refer to here
For example
[FunctionName("GetBookingCalendarsFunction")]
[QueryStringParameter("name", "this is name", DataType = typeof(string), Required = false)]
[QueryStringParameter("email", "this is email", DataType = typeof(string), Required = false)]
[QueryStringParameter("phone", "this is phone", DataType = typeof(string), Required = false)]
public static async Task<IActionResult> GetAllAsync(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "bookings")] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
return new OkObjectResult($"Name: {req.Query["name"]}, email: {req.Query["email"]}, phone: {req.Query["phone"]}");
}
Is there a better way to set bearer like a global config rather than setting it each time like this:
restClient.setBearerAuth(TokenStore.getInstance().getLocalToken());
The same for root url, is there a global config rather than setting it like this:
String root= Application.getInstance().getApplicationContext().getResources().getString(R.string.whiteLabelApiBaseHost)
restClient.setRootUrl(root);
In retrofit, there is something like this:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Application.getInstance().getApplicationContext()
.getResources().getString(R.string.whiteLabelApiBaseHost))
Any idea?
To set root url you can use this method, substituting the string with a constant
#Rest(rootUrl = "http://company.com/ajax/services", converters = { MappingJackson2HttpMessageConverter.class }, interceptors = MyAuthInterceptor.class)
public interface MyRestClient {
#Get("/events")
EventList getEvents();
}
Note that we set an interceptor in the arguments of the #Rest annotation.
So create a class like this:
#EBean(scope = Scope.Singleton)
public class MyAuthInterceptor implements ClientHttpRequestInterceptor {
#Bean
MyAuthStore authStore;
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
HttpHeaders headers = request.getHeaders();
HttpAuthentication auth = new HttpBasicAuthentication(authStore.getUsername(), authStore.getPassword());
headers.setAuthorization(auth);
return execution.execute(request, body);
}
}
Now before executing request MyAuthInterceptor.intercept() is called and you can set your authentication data as you prefer
In your main build.gradle file you can add inside android element
productFlavors {
development {
buildConfigField "String", "SERVICE_URL_BASE", "\"dev.xxx.com/rest\""
}
test {
buildConfigField "String", "SERVICE_URL_BASE", "\"test.xxx.com/rest\""
}
production {
buildConfigField "String", "SERVICE_URL_BASE", "\"production.xxx.com/rest\""
}
}
Then in your #Rest annotation you can use this code to get current flavor value:
#Rest(rootUrl = "https://" + BuildConfig.SERVICE_URL_BASE)
Now you can select what build variant to use (variant = flavor + buildType) to use desired value. To select variant you can use corresponding view, it should be present on the left of android studio.
This technique is useful to avoid creating flavor's package tree only to use different variabiles