youtube api in c# code - c#

using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://www.googleapis.com/youtube/v3/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("search?q=manam&type=video&order=relevance&part=snippet&maxResults=50&key=AIzaSyA4GZFAgfvsAItwFRmnAZvbTHoDeyunf2k").Result;
if (response.IsSuccessStatusCode)
{
dynamic lists = await response.Content.ReadAsAsync<mycustomObject>(); // what should I write here
}
}
I am trying to get the youtube videos with web api call in my project.
This is the code what I tried till now,
to get the response what should I use in the place of myCustomObject ?
when I am trying with the above url in browser I am getting the data, when I ran above code it return null,
Anything wrong with above code?
I just want to get the data from this method,
Any help will be greatly appreciated.

You need a class which represents the JSON data being returned from the call.
If you call your GET request in a browser you'll see the JSON response looks something like this:
{
kind: "youtube#searchListResponse"
etag: ""tbWC5XrSXxe1WOAx6MK9z4hHSU8/lh-waoy9ByBY2eB-oZs7niK51FU""
nextPageToken: "CDIQAA"
pageInfo:
{
totalResults: 176872
resultsPerPage: 50
}-
items: [...50]-
}
So you need to create a class with matching fields which the deserialize command will then populate for you. Something like this:
public class YoutubeApiResponse()
{
public string kind {get; set;}
public string etag {get; set;}
public string nextPageToken {get; set;}
public PageInfo pageInfo {get; set;}
public List<Item> items {get; set;}
}
And call like this:
var youtubeResponse = await response.Content.ReadAsAsync<YoutubeApiResponse().Result();
I'd recommend looking at the .Net Client Library - it will take care of a lot of this stuff for you.

Related

RESTsharp get command with &

Hey all this is the first time I am trying out RESTsharp. I am trying to create a GET call that looks like this:
http://labs.bible.org/api/?passage=random&type=json
I've tried the following with looking at some online examples:
var client = new RestClient("http://labs.bible.org/");
var request = new RestRequest("api/?{0}&{1}", Method.GET);
request.AddParameter("passage", "random");
request.AddParameter("type", "json");
var queryResult = client.Execute<List<quotesAPI>>(request).Data;
When I put a stop on the queryResult it just says NULL.
quotesAPI looks like this:
public class qAPI
{
public string bookname { get; set; }
public string chapter { get; set; }
public string verse { get; set; }
public string text { get; set; }
}
So how do I need to format the call in order for it to work as it should be?
update 1
var client = new RestClient("http://labs.bible.org/");
var request = new RestRequest("api", Method.GET);
request.AddParameter("passage", "random");
request.AddParameter("type", "json");
client.AddHandler("application/x-javascript", new RestSharp.Deserializers.JsonDeserializer());
var queryResult = client.Execute<List<quotesAPI>>(request).Data;
First, there is no need to create rest client like this:
new RestRequest("api/?{0}&{1}", Method.GET);
This will result in query to http://labs.bible.org/api/?{0}&{1}&passage=random&type=json. In this specific case it might still "work", but in general you should of course avoid this. Instead, create it like this:
new RestRequest("api", Method.GET);
For GET methods, parameters you then create will be appended to query string for you.
Another problem here is unusual content type of response. Response for your query has content type application/x-javascript. RestSharp has no idea what to do with such content type, so you should tell it:
var client = new RestClient("http://labs.bible.org/");
client.AddHandler("application/x-javascript", new RestSharp.Deserializers.JsonDeserializer());
Here you say that it should deserialize response with such content type as json. After that you should receive expected result.

Restsharp getting especific JSON value from content

I'm trying to get a specific value from my content, but I don't have any idea how I can do it.
I'm using RestSharp(C#) to run my JSON code, but when I execute the command it returns an error. I need to get the value from the property errorMessage.
var json = JsonConvert.SerializeObject(objectToUpdate);
var request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddCookie("authToken", token);
request.AddParameter("application/json", json, ParameterType.RequestBody);
var response = client.Execute<T>(request);
After execute this code my response return the below JSON:
{
"response":{},
"status":{
"success":false,
"detail":{
"errormessage":[{
"fieldName":"departmentCode",
"errorMessage":"Department code provided is already associated with another department",
"errorCode":"DUPLICATE_DEPARTMENT_CODE"
}],
"error":"Validation failure on request",
"operation":"internal",
"errorcode":"412"
}
}
}
You could have a class, that represents the response you expect:
class ApiResponse{
// use a class that represents normal response instead of object
// if you need to interact with it.
public object Response {get; set;}
public ResponseStatus Status{get; set;}
}
class ResponseStatus {
public StatusDetail Detail{get; set;}
public bool Success {get; set;}
}
class StatusDetail {
public ErrorMessage[] ErrorMessage{get; set;}
}
class ErrorMessage{
public string FieldName{get; set;}
public string ErrorMessage{get; set;}
public string ErrorCode{get; set;}
}
Then you have that, you can get parsed response from RestSharp client:
var response = client.Execute<ApiResponse>(request);
var message = response.Data.Response.Detail.ErrorMessage.First().ErrorMessage;
According to RestSharp docs, they recomment using response classes over dynamic objects (https://github.com/restsharp/RestSharp/wiki/Recommended-Usage).

HttpClient ReadAsAsync<Type> only deserializing part of the response

I am using the following to make a call to a WebAPI
using (HttpClient client = HttpClientFactory.Create(new AuthorisationHandler()))
{
client.BaseAddress = new Uri(BaseURI);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/xml"));
var httpResponseMessage = await client.PostAsXmlAsync<AvailRequest>("Avail/Search/", req);
httpResponseMessage.EnsureSuccessStatusCode();
var availResp = await httpResponseMessage.Content.ReadAsAsync<AvailResponse>();
return availResp;
}
the AvailResponse class looks something like this
[DataContract(Namespace = "")]
public class AvailResponse
{
[DataMember]
public ICollection<NotWorkingType> NotWorking { get; set; }
[DataMember]
public ICollection<WorkingType> Working { get; set; }
}
for some reason - clearly unknown to me - when the response comes in and is parsed into the AvailResponse object only the WorkingType is de-serialised and the other NotWorking one is not. I have used fiddler and can confirm that the response has both these in i.
I have tried using a XmlMediaTypeFormatter in place of the default and even setting the UseXmlSerialiser to true, but to no avail.
could someone shed some light on what is going on please
I would have thought that if it is not going to deserialise properly it would chuck and error rather than simply deserialising a part of the response.
any help as ever much appreciated
thanks
nat

How to correctly deserialise JSONArrays using RestSharp

How do I correctly deserialise the results of this call (you can click to see output):
https://bitpay.com/api/rates
I'm using a POCO object like this:
public class BitpayPrice
{
public string code { get; set; }
public string name { get; set; }
public double rate { get; set; }
}
And I'm calling the API like so:
var client = new RestClient();
client.BaseUrl = "https://bitpay.com";
var request = new RestRequest("/api/rates", Method.GET);
var response = client.Execute<BitpayPrice[]>(request);
Now, I know that the call to execute is wrong, but how do I un-wrongify it? I'd like to get back an array of BitcoinPrice objects.
RestSharp doesn't support deserializing into array, the best you can get is a List<>:
var response = client.Execute<List<BitpayPrice>>(request);
The reason is that types that you can deserialize to are required to have public parameterless constructor (for performance reasons mostly).

ServiceStack: JsonServiceClient usage without IReturn in DTO

What I would like to do is the following:
var client = new JsonServiceClient(ServiceUrl);
var request = new FooQuery {Id = 1};
IEnumerable<Project> response = client.Get(request);
However, my FooQuery doesn't implement any IReturn, and I'd like it not to (it's in a library without ServiceStack references). Here's my service side:
Library of business objects:
public class ProjectQuery
{
public int Id { get; set; }
}
AppHost:
Routes.Add<ProjectQuery>("/project", "GET");
Service:
public object Get(Foo request)
{
// do stuff.
}
Is there some nice, clean way to create the JsonServiceClient without using the IReturn interface on my business object?
Looks like there's no way not to use IReturn if you don't want to provide a URL to the JsonServiceClient Get() requests. Just decided to create another set of DTOs in my ServiceStack implementation, that are essentially mirrors of the real DTOs in another library. Then when a request comes in to my SS DTO, I create the other library's DTO, set each property, and pass it along.
Not pretty, but that's the best I could find so far.
I had the same problem using IReturn and Routes, as I wanted to use the DTOs
in assemblies with business logic, without ServiceStack references.
It worked for me, using in the Client Model
public class TestRequest
{
public int vendorId {get; set; }
public string barcode {get; set; }
public string username { get; set; }
public string password { get; set; }
}
then in the AppHost
Routes.Add<TestRequest( "/TestAPI/Reservation/{vendorId}/{barcode}"," GET,OPTIONS")
.Add<TestRequest>("/TestAPI/Reservation", "POST, OPTIONS")
and the call for JsonServiceClient with POST
request.vendorId=12344;
request.barcode="AAS1223";
TestResponse response = client.Post<TestResponse>(server_ip + "/TestAPI/Reservation", request);
OR with GET
TestResponse response = client.Get<TestResponse>(server_ip + "/TestAPI/Reservation/12344/AAS1223?username=John&password=99");
Then in the service Get or Post functions
public TestResponse Get(TestRequest request)
{
// request members hold the values of the url.
return DoBusinessLayerWork(request);
}
Using the Send() method from the JsonServiceClient type is the way to go about doing this.

Categories