I have Swagger UI 3.19.4 and I want to create REST requests like following:
GET https://<host>/<path>?select=*
It means that I want to add query parameter select=* in each get request that will be sent from Swagger UI.
How can I do that?
My solution is to use requestInterceptor
SwaggerUiBundle({
...,
requestInterceptor: (request) => {
uri = new URI(request.uri);
uri.selectParams.append("select", "*");
request.uri = uri.toString();
//code
return request;
}
})
I decided to use requestInterceptor, because it is official way to modify requests from SwaggerUI https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/.
Also to modify URL you can use standard class URL (JavaScript).
Related
I need to call rest api for example:
let developerId ="123#212";
let url = `${Constants.BASE_URL}${marketId}/developers/${developerId}`;
return this.http.get(url);
But backend only getting 123 instead of 123#212
What I tried so far is to do but not working
Using encodeURIComponent
encodeURIComponent(${developerId})
Using HttpInterceptor
same with https://stackoverflow.com/a/54524089
Calling the rest api using Postman perfectly working but not in Angular
Instead of sending this with hashtag use HttpParams to send this data you can see the same being used in the question you mentioned.
In your post/get request you can add this
this.http.get('URL', {
params: new HttpParams()
.set('param-a', 'value-1')
.set('param-2', 5)
})
Good Evening,
I have a function that contains a route that is a call to the Auth0 API and contains the updated data that was sent from the client. The function runs, but the app.patch() does not seem to run and I am not sure what I am missing.
function updateUser(val) {
app.patch(`https://${process.env.AUTH0_BASE_URL}/api/v2/users/${val.id}`,(res) => {
console.log(val);
res.header('Authorization: Bearer <insert token>)
res.json(val);
})
app.post('/updateuser', (req, ) => {
const val = req.body;
updateUser(val);
})
app.patch() does NOT send an outgoing request to another server. Instead, it registers a listener for incoming PATCH requests. It does not appear from your comments that that is what you want to do.
To send a PATCH request to another server, you need to use a library that is designed for sending http requests. There's a low level library built into the nodejs http module which you could use an http.request() to construct a PATCH request with, but it's generally a lot easier to use a higher level library such as any of them listed here.
My favorite in that list is the got() library, but many in that list are popular and used widely.
Using the got() library, you would send a PATCH request like this:
const got = require('got');
const options = {
headers: {Authorization: `Bearer ${someToken}`},
body: someData
};
const url = `https://${process.env.AUTH0_BASE_URL}/api/v2/users/${val.id}`;
got.patch(url, options).then(result => {
console.log(result);
}).catch(err => {
console.log(err);
});
Note: The PATCH request needs body data (the same that a POST needs body data)
I am trying to get information from a fantasy data API using AngularJS. I am using $resource to perform my get request in my controller, but I haven't been able to figure out how to correctly include the API key. Do I need to include it as a header? Thanks.
nflApp.controller('mainController', ['$scope','$resource','$routeParams', function($scope, $resource, $routeParams) {
$scope.fantasyAPI = $resource("https://api.fantasydata.net/nfl/v2/JSON/DailyFantasyPlayers/2015-DEC-28", { callback: "JSON_CALLBACK" }, { get: { method: "JSONP"}});
console.log($scope.fantasyAPI);
}]);
Below is the http request info from the site.
You should set a header with the API key, AngularJS will send them with every request in the following case:
$http.defaults.headers.common["Ocp-Apim-Subscription-Key"] = key;
When adding '.common' you are telling angular to send this in every request so you do not need to add it to every resource that hits the API.
A easy way to do that is by creating your own interceptors from $httpProvider at "config" fase.
To do that, just write something like:
mymodule.config(['$httpProvider', function($httpProvider){
$httpProvider.interceptors.push(function ($q) {
return {
'request': function (config) {
config.headers['Ocp-Apim-Subscription-Key'] = SomeUserClass.AuthToken();
return config;
},
'response': function (response) {
return response;
}
};
});
});
You need to modify request header in JSONP. Unfortunately it is not possible. As the browser is responsible for header creation and you just can't manipulate that when using JSONP method.
how to change the headers for angularjs $http.jsonp
Set Headers with jQuery.ajax and JSONP?
From that link - https://johnnywey.wordpress.com/2012/05/20/jsonp-how-does-it-work/
Why NOT To Use JSONP?
Deciding against using JSONP is directly related to how it works. First of all, the only HTTP method you can use is GET since that is the only method script tags support. This immediately eliminates the use of JSONP as an option to interact with nice RESTful APIs that use other HTTP verbs to do fun stuff like CRUD. And while we’re on the subject of GET, note that using anything other than URL parameters to communicate with the server API (e.g. sending some JSON over) is also not possible. (You could encode JSON as a URL parameter, but shame on you for even thinking that.)
If they only work with header manipulation you will need to do that call from your server side.
I have a JQGrid and search filters and loadOnce=false. I search records in grid and i am able to see this json GET type in firebug.
http://localhost:8080/myapp/items/listGrid?ticketId=&_search=true&nd=1393573713370&rows=20&page=1&sidx=id&sord=asc&filters=%7B%22groupOp%22%3A%22AND%22%2C%22rules%22%3A%5B%7B%22field%22%3A%22summary%22%2C%22op%22%3A%22cn%22%2C%22data%22%3A%22Test%22%7D%5D%7D
I want to get this JSON request URL after this request completed I have to add same params to my pdf link.
I try
document.URL
window.location.pathname
jQuery("#itemsGrid").jqGrid('getGridParam', 'url');
output
"localhost:8080/myapp/items/list"
"/myapp/items/list"
"/myapp/items/listGrid?ticketId="
How can I get the same URL?
If it is an ajax call you could decorate the XMLHttpRequest.prototype.open function:
var calls = [];
XMLHttpRequest.prototype._originalOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
if(method === 'GET') // Only add GET requests
calls.push(url);
this._originalOpen(method, url, async, user, password);
}
Now you can access the last get URL as follows
var lastUrl = calls[calls.length - 1]
Adopted this code from this SO question.
If you need to append the URL with additional parameters you should use postData parameter of jqGrid. I recommend to define parameters as functions (like in the answer). If you need to send user credentials information then you should better place it in custom HTTP headers instead of URL which can be seen by everybody. Usage of loadBeforeSend callback would be the best choice in the case. See the answer and this one for the code example. One more option which you have is the usage of beforeRequest callback to modify url parameter of jqGrid directly before the usage (see the answer)
The usage of https: instead of http: in the final solution would be recommend too.
My app is Backbone.js for client-side, Express.js for back-end.
I have problems with syncing with all parts of my API, using the backbone model and collection(they use urlRoot: "/users").
I'm allowed to use only GET or POST, no PUT or DELETE.
*I'm not allowed to use more models*
Not allowed to use jQuery ajax
My API
add new user:
I need to make a POST to /users with JSON of new data. So I did it just fine with - this.model.save({new data...})
list all users:
My API for that, responses to GET /users, with the right handler - so, this.collection.fetch() - works fine.
Log-In:
My API accepts POST to /users/login for that. How can I add a function "logIn" to my model, that will use custom sync/pass options.url to sync - or any other way - that will POST to /users/login ?
Log-Out:
API accepts POST to /users/logout - how to send this request using my backbone model ?
User By ID:
Same question here for GET /users/:id
Update user:
POST /users/:id - same question again.
--- So actually, the question in short is ---
What is the best way (or the most "right"), to implement methods of a backbone model, that are similar to "model.save()" - but just POST/GET to a bit different path then urlRoot ?
You probably have a couple options here. One would be structuring your models in a way that supports the urls you want. For instance, have a User model and a Session model that deal with updating the user and managing the logged in state separately.
The other thing you should probably do is to use the url method in your models.
Something like this in your User model. (Note: using urlRoot instead of url here is identical, but this is the correct approach for anything more complicated that is needed in the url)
url : function() {
var base = "/users/";
if(this.isNew()) {
return base;
} else {
return base + this.get("id");
}
}
You could extend this same concept to work in your Session model for handling logout vs login based on if the Session is new or not.
Update:
If you must use the same model, the best thing would be to totally bypass the Backbone.sync method and write a custom AJAX call with success/error handlers that know how to clean things up.
login : function() {
$.post("/users/login", {success: function (response) {
// Update user as needed
}, error: function (xhr, response) {
// Handle errors
}
}
}