I have an endpoint like this:
#Controller(['route1', 'route2'])
export class test {
#Post('endpoint')
public test() { return; }
}
The swagger than generates two routes:
'/route1/endpoint' and '/route2/endpoint'
I would like this to only generate one endpoint in the swagger documentation of '/endpoint', but then say in the documentation above the different routes the user can use to call the endpoint. Is there any way I can edit these and only show one?
Related
I am developing a rest application.
Some endpoints require a custom header parameter, not related to authorisation. I created a custom annotation using jax-rs NameBinding. Here is an usage example:
#GET
#RequiresBankHeader
public int get(
#HeaderParam("bank")
#Parameter(ref = "#/components/parameters/banks")
String bank) {
return someService.getSomeInformation();
}
There is a provider that intercepts this call and do some routine using the information in the header parameter.
The problem is that I have to repeat '#HeaderParam("bank") #Parameter(ref = "#/components/parameters/banks") String bank' everywhere, just so it appears in Swagger, even though the service classes do not need it. I was able to at least reuse the parameter definition with ref = "#/components/parameters/banks", and declaring it in the OpenAPI.yml file, that Quarkus merges with generated code very nicely.
But I also want to create and interceptor to dynamically add this do the OpenApi definition whenever RequiresBankHeader annotation is present.
Is there a way to do it?
I dont think you can use interceptors to modify the generated Openapi schema output.
If all methods on a given endpoint require some parameter, you can specify it on class level like so:
#Path("/someendpoint")
public class MyEndpoint {
#HeaderParam("bank")
#Parameter(name = "bank")
String bank;
#GET
public Response getAll() {return Response.ok().build()}
#GET
#Path("{id}")
public Response someMethod(#PathParam("id") String id) {return Response.ok().build();}
}
As mentioned by Roberto Cortez, the MP OpenAPI spec provides a programmatic way to contribute metadata to the openapi.yml file.
It is not possible to detect an annotation in the JAX-RS endpoint definition, but it was good enough to automate what I needed. Since all methods that had the RequiresBankHeader return the same Schema, I was able to hack it like this:
public class OpenApiConfigurator implements OASFilter {
#Override
public Operation filterOperation(Operation operation) {
operation.getResponses().getAPIResponses().values().stream().
map(APIResponse::getContent).
filter(Objects::nonNull).
map(Content::getMediaTypes).
flatMap(mediaTypes -> mediaTypes.values().stream()).
map(MediaType::getSchema).
filter(Objects::nonNull).
map(Schema::getRef).
filter(Objects::nonNull).
filter(ref -> ref.contains("the common response schema")).
findAny().
ifPresent(schema -> {
ParameterImpl parameter = new ParameterImpl();
parameter.setRef("#/components/parameters/banks");
operation.addParameter(parameter);
});
return operation;
}
OpenApiConfigurator should be configure in the application properties, using mp.openapi.filter=com.yourcompany.OpenApiConfigurator
My GET method WORKS fine when I use the url logged in as SuperUser like this(I get the name of the first user pulled from the DB):
http://localhost/DesktopModules/AAAA_MyChatServer/API/ChatApi/GetMessage
But I cannot access the POST method in the same controller either using AJAX from view or just by entering the url (post method doesnt get hit/found):
http://localhost/DesktopModules/AAAA_MyChatServer/API/ChatApi/SendMessage
And also this fails as well:
$('#sendChat').click(function (e) {
e.preventDefault();
var user = '#Model.CurrentUserInfo.DisplayName';
var message = $('#chatBoxReplyArea').val();
var url = '/DesktopModules/AAAA_MyChatServer/API/ChatApi/SendMessage';
$.post(url, { user: user, message: message }, function (data) {
}).done(function () {
});
});
The Error message is:
<Error>
<Message>
No HTTP resource was found that matches the request URI 'http://localhost/DesktopModules/AAAA_MyChatServer/API/ChatApi/SendMessage'.
</Message>
<MessageDetail>
No action was found on the controller 'ChatApi' that matches the name 'SendMessage'.
</MessageDetail>
</Error>
And sometimes:
"The controller does not support GET method"
even though I do have both a GET and a POST there and the GET works. What am I missing?
I have made a routing class in my DNN project:
using DotNetNuke.Web.Api;
namespace AAAA.MyChatServer
{
public class RouteMapper : IServiceRouteMapper
{
public void RegisterRoutes(IMapRoute mapRouteManager)
{
mapRouteManager.MapHttpRoute("MyChatServer", "default", "{controller}/{action}", new[] { "AAAA.MyChatServer.Services" });
}
}
}
I added a DNN Api Controller in folder Services of my project named AAAA.MyChatServer:
using DotNetNuke.Web.Api;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
namespace AAAA.MyChatServer.Services
{
[DnnAuthorize(StaticRoles = "SuperUser")]
public class ChatApiController : DnnApiController
{
[HttpGet]
public HttpResponseMessage GetMessage()
{
ChatServerManager csm = new ChatServerManager();
var users = csm.GetAllUsers();
var user = users.FirstOrDefault().Name;
return Request.CreateResponse(System.Net.HttpStatusCode.OK, user);
}
[System.Web.Http.HttpPost]
public HttpResponseMessage SendMessage(string toUser, string message)
{
return Request.CreateResponse(System.Net.HttpStatusCode.OK);
}
}
}
There are two ways to call a POST method in a DNN WebAPI: with parameters and with an object. If you use parameters, as you have in your SendMessage method, those parameter values need to be delivered via the Query String.
On the other hand, creating an object and sending that with your call to the WebAPI method can handle a great many more scenarios and is arguably a better way of handling any POST method (as it hides those values from prying eyes, making the call more difficult to counterfeit). To handle this, you can remove the parameters from your SendMessage method and instead interrogate the HttpContext.Current.Request object within your method. The object you created { user: user, message: message } will be nestled in there somewhere.
As it is written in your example, your object was sailing past your parameters like two ships in the night.
I've only just figured this out myself, and I don't have all the understanding I need yet, but hopefully this will help you along your way. Here are some articles I referenced in my quest to use cURL to upload a file to my DNN WebAPI:
https://www.dnnsoftware.com/community-blog/cid/134676/getting-started-with-dotnetnuke-services-framework
https://www.dnnsoftware.com/community-blog/cid/144400/webapi-tips
How To Accept a File POST
https://forums.asp.net/t/2104884.aspx?Uploading+a+file+using+webapi+C+
https://talkdotnet.wordpress.com/2014/03/18/dotnetnuke-webapi-helloworld-example-part-one/comment-page-1/
http://dnnmodule.com/Article/ArticleDetail/tabid/111/ArticleId/511/Dotnetnuke-7-0-WebAPI-Tips.aspx
How to post file using Curl in WebApi in Asp.Net MVC
Good luck!
Your Web Api for SendMessage contain 2 parameter, so it should POST in query string :
http://localhost/DesktopModules/AAAA_MyChatServer/API/ChatApi/SendMessage?touser=john&message=hello
if you want to POST it using data of object, you need to make the Web Service parameter as object model
Also your javascript parameter is different from the Web Service, as it use "toUser"
In my UrlMappings I have this mapping defined :
"/$controller/$action?/$id?(.$format)?"{}
and now I want to add a set of version 2 services.
for example :
A new service at URI : /api/myaction
and I want to be able define a new endpoint /api/v2/myaction , where myaction will map to a new action called myactionV2
There are a number of ways to do this and the best solution depends on some factors that you haven't included in your question. Here is a solution that most closely maps to the question and a comment that the OP added above.
See the project at https://github.com/jeffbrown/javaheadendpoints.
https://github.com/jeffbrown/javaheadendpoints/blob/47f41b3943422c3c9e44a08ac646ecb2046972d1/grails-app/controllers/demo/v1/ApiController.groovy
package demo.v1
class ApiController {
static namespace = 'v1'
def myaction() {
render 'This request was handled by version 1 of the api'
}
}
https://github.com/jeffbrown/javaheadendpoints/blob/47f41b3943422c3c9e44a08ac646ecb2046972d1/grails-app/controllers/demo/v2/ApiController.groovy
package demo.v2
class ApiController {
static namespace = 'v2'
def myaction() {
render 'This request was handled by version 2 of the api'
}
}
https://github.com/jeffbrown/javaheadendpoints/blob/47f41b3943422c3c9e44a08ac646ecb2046972d1/grails-app/controllers/demo/v3/ApiController.groovy
package demo.v3
class ApiController {
static namespace = 'v3'
def myaction() {
render 'This request was handled by version 3 of the api'
}
}
https://github.com/jeffbrown/javaheadendpoints/blob/47f41b3943422c3c9e44a08ac646ecb2046972d1/grails-app/controllers/javaheadendpoints/UrlMappings.groovy
package javaheadendpoints
class UrlMappings {
static mappings = {
"/$controller/$action?/$id?(.$format)?"{
constraints {
// apply constraints here
}
}
"/$controller/$namespace/$action/$id?(.$format)?" {
// ...
}
"/"(view:"/index")
"500"(view:'/error')
"404"(view:'/notFound')
}
}
Sending requests yields what I think is the requested behavior:
$ curl http://localhost:8080/api/v1/myaction
This request was handled by version 1 of the api
$ curl http://localhost:8080/api/v2/myaction
This request was handled by version 2 of the api
$ curl http://localhost:8080/api/v3/myaction
This request was handled by version 3 of the api
Other options include using a Version http header but because of some of the wording above, I think that is not going to be exactly what you want.
I hope that helps.
not suppose to do that,The way i suggest is to split in two controller
/api1/myaction
/api2/myaction
or in action
/api/myaction1
/api/myaction2
I'm attempting to implement a RESTful API using Grails 2.5.5, and I'm running into a few issues.
It appears that Grails does not automatically map any methods for the corresponding HTTP methods, so I'm editing UrlMappings.groovy.
For example, take the following URLs:
GET /v1/1/persons/ <--- List of persons
POST /v1/1/persons/ <--- Create a new person
PUT /v1/1/persons/1234 <--- Edit person with ID of 1234
These are my url mappings:
"/v1/$appId/$controller/$action?/$id?(.$format)?" {
namespace = "v1"
}
"/v1/$appId/$controller"(action: "save", method: "POST") {
namespace = "v1"
}
"/v1/$appId/$controller/$id"(action: "update", method: "PUT") {
namespace = "v1"
}
So now, the first mapping will handle the GET request in my example urls as well as other generic urls.
The second mapping will handle the second url from my example urls.
And lastly, the third mapping handles the third url from my example urls.
The issue I'm facing now is that my command object isn't getting bound properly for my PUT request. The POST request works fine however.
These are my methods:
def save(MyCommand cmd) {
// works great
}
def update(MyCommand cmd) {
// cmd properties are null
// params.id is bound though. So I'm getting the path variable.
}
As you can see, the logic is very simple.
But I'm completely stumped as to why I can't get the request body in the PUT method.
Additional question: How can I get the above urls to work in addition to this url?:
/v1/1/persons/1234/status
I tried the following mapping, but it does not seem to work:
"/v1/$appId/$controller/$id/$action" {
namespace = "v1"
}
It feels like I'm stuck in this URLMappings hell!
How do I define basic authentication using Swagger 2.0 annotations and have it display in swagger UI.
In the resource I have:
#ApiOperation(value = "Return list of categories", response=Category.class, responseContainer="List", httpMethod="GET", authorizations = {#Authorization(value="basicAuth")})
public Response getCategories();
I looked here:
https://github.com/swagger-api/swagger-core/wiki/Annotations#authorization-authorizationscope
And it says "Once you've declared and configured which authorization schemes you support in your API, you can use these annotation to note which authorization scheme is required on a resource or a specific operation" But I can't find anything that talks about where to declare and configure the authorization schemes.
Update:
I found code on how to declare the schema, but I still do not see any information about the authentication schema in the UI. I'm not sure what I am missing
#SwaggerDefinition
public class MyApiDefinition implements ReaderListener {
public static final String BASIC_AUTH_SCHEME = "basicAuth";
#Override
public void beforeScan(Reader reader, Swagger swagger) {
}
#Override
public void afterScan(Reader reader, Swagger swagger) {
BasicAuthDefinition basicAuthDefinition = new BasicAuthDefinition();
swagger.addSecurityDefinition(BASIC_AUTH_SCHEME, basicAuthDefinition);
}
}
Using Springfox 2.6 annotations, you must first define Basic authentication as one of the security schemes when you set up the Docket in your configuration, like this:
List<SecurityScheme> schemeList = new ArrayList<>();
schemeList.add(new BasicAuth("basicAuth"));
return new
Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo)
.securitySchemes(schemeList)
...
Then you can use the Springfox annotations in your service to set Basic Auth for the operation for which you want to require authentication:
#ApiOperation(value = "Return list of categories", response=Category.class, responseContainer="List", httpMethod="GET", authorizations = {#Authorization(value="basicAuth")})
public Response getCategories();
I struggeled with this as well. In my case i used the swagger-maven-plugin. To solve this i added this within the maven plugin:
<securityDefinitions>
<securityDefinition>
<name>basicAuth</name>
<type>basic</type>
</securityDefinition>
</securityDefinitions>
After that i was able to add it on my resource like this:
#Api(value = "My REST Interface", authorizations = {#Authorization(value="basicAuth")})
The generated json included the security element for each endpoint:
"security":[{
"basicAuth" : []
}]
And the security definition:
"securityDefinitions" : {
"basicAuth" : {
"type" : "basic"
}
}
I hope this helps others as well.
You can use the #SwaggerDefinition
http://swagger.io/customizing-your-auto-generated-swagger-definitions-in-1-5-x/
or you can configure the swagger object directly, here's an example
http://www.programcreek.com/java-api-examples/index.php?source_dir=rakam-master/rakam/src/main/java/org/rakam/WebServiceRecipe.java