Make GET call to REST service with parameters in Angular 2 - angularjs

I am trying to make a GET call to the YouTube Web API but I cannot figure out how to pass parameters using the http.get function. I have used fiddler and made sure the request is being made. I am currently getting a 400 error saying that I am missing a the parameter "Part". How can I modify my code to include the required parameters in my request?
private _url = 'https://www.googleapis.com/youtube/v3/';
private _key = '';
getPlaylistVideos(playlistId, pageToken){
var url = this._url + "playlistItems";
var options = { part: 'snippet', maxResults: 50, playlistId: playlistId, key: this._key, pageToken: pageToken }
return this.http.get(url, options);
}

You need to include the search params in to your request. I think this will work for you:
getPlaylistVideos(playlistId, pageToken) {
let url = `${this._url}playlistItems`,
options = { part: 'snippet', maxResults: 50, playlistId: playlistId, key: this._key, pageToken: pageToken },
params = URLSearchParams();
for (let key in options) params.set(key, options[key);
return this.http.get(url, {search: options});
}
You create the URLSearchParams using the set method you can find the full documentation here

Please have a look at the already asked & solved question regarding AngularJS & YouTube V3 API. See here thanks to #Sandeep Sukhija.
Anyhow, about the missing parameter part, add it to the request ex: part: 'snippet'
Example code :
function getPlaylistVideos(playlistId, pageToken) {
// pass the page token as a parameter to the API
$.get('https://www.googleapis.com/youtube/v3/playlistItems', { part: 'snippet', maxResults: 50, playlistId: playlistId, key: key, pageToken: pageToken })
}
How to use the part parameter
The part parameter is a required parameter for any API request that
retrieves or returns a resource. The parameter identifies one or more
top-level (non-nested) resource properties that should be included in
an API response. For example, a video resource has the following
parts:
snippet contentDetails fileDetails player processingDetails
recordingDetails statistics status suggestions topicDetails

Related

JSON POST request sends only id

Hello Everyone I couldn't find any solution so here is my question
I tried to write POST Request and tried to POST data as JSON, it works
but I only get new Object in JSON file with new ID, nothing else is being sent.
This is ReaactJS app to be exact
var url = 'http://localhost:3000/applications'; //Configurable endpoint
var request = new XMLHttpRequest();
var isSent = false;
var data = {
name : this.state.name,
age : this.state.age,
prefix : this.state.prefix,
email : this.state.email
}
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onload = function () {
isSent = true;
console.log(this.responseText);
};
xhr.send(data);
This is my way to do so
You should check out new fetch API.
The Fetch API provides an interface for fetching resources (including across the network). It will seem familiar to anyone who has used XMLHttpRequest, but the new API provides a more powerful and flexible feature set.
Please check Fetch: POST json data
The problem night be with the formatting of the .rest file
For example
POST http://localhost:3001/api/persons
Content-Type: application/json
{
"name" : "fbgjdbh",
"number" : 89475947
}
this worked for me. You need to leave an empty line after the content-type, then specify the object.
The following was not working for me and was only sending the id.
POST http://localhost:3001/api/persons
Content-Type: application/json
{
"name" : "fbgjdbh",
"number" : 89475947
}

Angular 2 http get querystring params

Hopefully someone can help with this. I building an ionic 2 app which is based on the newer Angular 2, I am familiar with previous versions of Angular, but still trying to figure this whole typescript.
I have my API setup with basic get querystrings (e.g domain.com?state=ca&city=somename)
export class TestPage {
public state: string ='ca';
public city: string = null;
constructor(private http: Http){}
public submit() {
let url = "http://localhost/api";
let payload = {"state": this.state, "city": this.city};
this.$http.get(url, payload).subscribe(result => {
//result
}, err => {
//do something with the error
}
)
}
}
When I execute this it pulls my API url fine and I can get a response back, however none of the querystrings are being sent in the request. Its just sending http://localhost/api. If I console.log the payload its fine.
Ultimately I am trying to get it to do https://localhost/api?state=ca&city=example
Looking at examples I can't really find anything straight-forward on this.
Is it not possible to take a payload on http with this newer version of Angular? The code above is just an example. I have many querystrings, which is why I was hoping to send a payload to it.
Any help or suggestion would be appreciated.
The Http.get method takes an object that implements RequestOptionsArgs as a second parameter.
The search field of that object can be used to set a string or a URLSearchParams object.
An example:
// Parameters obj-
let params: URLSearchParams = new URLSearchParams();
params.set('state', this.state);
params.set('city', this.city);
//Http request-
return this.http.get('http://localhost/api', {
search: params
}).subscribe(
(response) => this.onGetForecastResult(response.json()),
(error) => this.onGetForecastError(error.json()),
() => this.onGetForecastComplete()
);
Documentation: here

REST AngularJS #resource parametrized request

I have next WEB API:
GET List<EventHistory> '/service/eventhistories'
GET EventHistory '/service/eventhistories/{id}'
DELETE EventHistory '/service/eventhistories/{id}'
PUT EventHistory '/service/eventhistories'
POST EventHistory '/service/eventhistories'
Using angular i want use #resource to get information from server.
angularApp.factory('eventHistoryFactory', function ($resource) {
return $resource('/inner/service/eventhistories/:id',{id:'#id'});
});
But using this declaration i do not have any API to request the page based on some data.
var pageRequest = {
size: size,
page: page
};
or to send update for eventHistory entity.
Based on OP's comment:
Say you want to update a single entity:
.controller('someCtrl', function($stateParams, eventHistoryFactory){
//For the sake of the demonstration - id comes from the state's params.
var eventHistory = eventHistoryFactory.get({id: $stateParams.id});
eventHistory.$promise.then(function(){
//Modify the entity when HTTP GET is complete
eventHistory.address = 'New York';
//Post the entity
eventHistory.$save();
//If you wish to use PUT instead of POST you should declare that
//in the class methods of $resource
});
//Another example using query
var entries = eventHistoryFactory.query({
page: 0,
size: 20,
before: Date.now()
});
//This is translated into GET /inner/service/eventhistories?page=0&size=20&before=111111111111
//and should be interpreted correctly by your backend.
entries.$promise.then(function(){
//entries now contain 20 first event history with date earlier than now.
var specificEntry = entries[0];
//Same deal - modify the entity when HTTP GET is complete
specificEntry.address = 'New York';
//Post the entity
specificEntry.$save();
});
the first answer seems good, but i think this way more understandable and simply for begginers:
eventHistoryFactory.get(pageRequest, function (returnData) {
console.trace('request processed successfully: ' + returnData);
params.total(returnData.totalElements);
$defer.resolve(returnData.content);
}, function (error) {
console.log('request processed with error: ' + error);
})
to make page request in dynamic way the object should be build before request from ngTable current properties (use ngTable API).
Please pay your attention to eventHistoryFactory. It does not have parameter for pageRequest object, but it works -angular magic. By GET request in url you can see:
?page=2&size=25

Add parameters to query string when using PUT method with Angular's $http

I'm using Angular's $http service to make web api requests. When I use the GET method, the two param values are added to the query string:
// http://foo.com/api/test?heroId=123&power=Death+ray
$http.get("/api/test", {
params: { heroId: 123, power : "Death ray" }
})
However, when I use the PUT method the params are JSON-encoded and sent as the request payload:
// {"params":{"heroId":123,"power":"Death ray"}}
$http.put("/api/test", {
params: { heroId: 123, power : "Death ray" }
})
How can I force the params to be added to the query string when using PUT?
With $http.put, $http.post or $http.patch, the config object containing your url parameters goes as the third argument, the second argument being the request body:
$http.put("/api/test", // 1. url
{}, // 2. request body
{ params: { heroId: 123, power : "Death ray" } } // 3. config object
);
$http.put documentation for reference
AngularJS send json data and not x-www-form-urlencoded format data.
Though you can try the below one:
$http.put("/api/test", { heroId: 123, power : "Death ray" });
If your api url is "api/test/heroId/power",
var data = 123+'/Death ray'
$http.put("api/test"+data);

Restangular post

I am trying to use restangular in my project, I have the set up and config all working fine.
I need to make a post request where i have the url and a json payload.
var url = xyz.com + "/api/v2/create?type=project";
eg payload
'{
"class":"Project",
"name":"test_project",
"description":"test_project",
"owner":{"class":"User","id":"2"},
"connection":{"class":"Connection","id":"1"},
"defaultNamespace":"default",
"namespaces":["default"]}'
I was unsure of how to make a restangular call, should the post have the payload as params?
I tried this below, but did not seem to work.
Restangular.all('create').post({
"class":"Project",
"name":"test_project",
"description":"test_project",
"owner":{"class":"User","id":"2"},
"connection":{"class":"Connection","id":"1"},
"defaultNamespace":"default",
"namespaces":["default"]})
Hey you should do something like:
Restangular.all('create').post(
// First the object
{
class: "Project",
name: "Test-project",
owner: {
class: "User"
}
},
// Then the request params
{type: "Project"}
);
That should do it :)

Resources