C# how to demonstrate api post from website - c#

I'm trying to program automation QA test to register.
I need to demonstrate a register request to api from specific website
This is my code
public void TestApi()
{
string apiStatus = "";
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://my_base_api_address");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//string fName = RegisterHandler.MakeNewUser();
var user = new RegisterModel()
{
public string UserEmail{ get; set; }
public int userId{ get; set; }
......
......
};
var response = client.PostAsJsonAsync("api/register/Register", user).Result;
if (response.IsSuccessStatusCode)
{
}
}
}
My code baseAddress is relevant to several websites but I need to test a specific one.
Where and how exactly should I put the testing website url?
Thanks in advance.

Related

PostAsJsonAsync C# - How to set headers correctly for POST request - BAD REQUEST 400

Hello to everyone out there.
I am having this next problem.
I am trying to do a POST request but when I am compiling and executing it with the debugger of Visual Studio Code, I am getting an error of 400 Bad Request.
Regardless of that, when I am doing the same POST request in Postman, I am getting a 200 OK status request with all the values that I need for continuing to the next part in which I am working on.
Moreover, there is a Basic Auth in the request which in this case I am including it in Postman and it works fine. From the other side, in my script with C#, I am executing it like this:
*This is my model in which all my data is included for serializing the object into JSON.
public class patientMediktor{
public string deviceId { get; set; }
public string deviceType { get; set; }
public string apiVersion { get; set; }
public string language { get; set; }
public externUserClass externUser{ get;set; }
public class externUserClass{
public externUserClass(string partnerExternalId, string username, string newPassword, string gender){
this.partnerExternalId = partnerExternalId;
this.username = username;
this.newPassword = newPassword;
this.gender = gender;
}
public string partnerExternalId { get; set; }
public string username { get; set; }
public string newPassword { get; set; }
public string gender { get; set; }
}
public string includeAuthToken{ get; set; }
}
*This is my Helper class for creating the POST request. I insert all the data that I need and then I serialize the object to JSON as some of you have adviced me to do so. It is quite cleaner.
public async Task<string> MediktorHubCrearUsuario(string conf, string userId, string sexo, string deviceId)
{
var sexoStr = "";
if(sexo == "MALE") {
sexoStr = "MALE";
} else if(sexo == "FEMALE") {
sexoStr = "FEMALE";
}
var guid = Guid.NewGuid().ToString(); // guid para el username y el password
var data = new patientMediktor();
data.deviceId = userId;
data.deviceType = "WEB";
data.apiVersion = "4.0.3";
data.language = "es_ES";
data.externUser = new patientMediktor.externUserClass(userId, guid, guid, sexoStr); // extern user
data.includeAuthToken = "true";
string output = JsonConvert.SerializeObject(data);
var ServerMedictor = conf;
var client = new HttpClient{BaseAddress = new Uri(ServerMedictor)};
MediaType = "application/json";
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaType)); //ACCEPT header
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("xxxxxx", "xxxxxxxxxxxx");
var Client = client;
var request = await Client.PostAsJsonAsync("externUser", output);
request.EnsureSuccessStatusCode();
var status = await request.Content.ReadAsStringAsync();
return status;
}
If anyone has any clue on how to deal with this, it would be really appreciating.
I will keep trying combinations on how to tackle with an alternative on the issue.
*Despite the modifications, I am still having the same issue. I did serialize the object and I am getting it the way I need to. But, whenever it comes to the request, it gives me a 400 Bad Request.
kind regards and thanks you
Try with PostAsync instead of 'PostAsJsonAsync'
var content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
var request = await httpClient.PostAsync(requestUrl, content);
Please find more details on 'PostAsJsonAsync' at HttpClient not supporting PostAsJsonAsync method C#
It seems you should remove the comma of the end of the following lines:
sexoStr = "\"gender\": \"MALE\",";
...
sexoStr = "\"gender\": \"FEMALE\",";
Generally speaking, prefer working with model class and serializing them (using Newtonsoft.Json (example) or System.Text.Json), instead of hardcoded strings.
The answer is here. The construction of the header of Basic Auth was wrong from the beginning. In order to encode it, I had to pass it like this new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)); and therefore to the request.
I also replaced the PostAsJsonAsync with PostAsync. It works like a charm!
Finally, I am getting a status code 200 OK with the data that I need to pass to my view.
public async Task<string> CreateUser(string conf, string userId, string sexo, string deviceId)
{
var sexoStr = "";
if(sexo == "MALE") {
sexoStr = "MALE";
} else if(sexo == "FEMALE") {
sexoStr = "FEMALE";
}
var guid = Guid.NewGuid().ToString(); // guid para el username y el password
var data = new patientMediktor();
data.deviceId = userId;
data.deviceType = "WEB";
data.apiVersion = "4.0.3";
data.language = "es_ES";
data.externUser = new patientMediktor.externUserClass(userId, guid, guid, sexoStr); // extern user
data.includeAuthToken = true;
string json = JsonConvert.SerializeObject(data);
var Client = new HttpClient();
var prueba = "https://xxxxxx.com:443/";
Client.BaseAddress = new Uri(prueba);
var byteArray = Encoding.ASCII.GetBytes("xxxxxxxx:xxxxxxxxx");
Client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var response = Client.PostAsync("backoffice/services/externUser", new StringContent(json, Encoding.UTF8, "application/json")).Result;
response.EnsureSuccessStatusCode();
var respuesta = await response.Content.ReadAsStringAsync();
return respuesta;
}

problem when trying to redeem the token for user information in the microsoft graph api

once the user logs in with his microsoft account in the web application, a redirection is made to a method which aims to extract the user code and exchange it for the token, finally when I try to use the token with the api , when making the http request through the get method, it fails, here I show the code, it was make on C#:
var EmailRequest = "https://graph.microsoft.com/v1.0/me/?$select=displayName";
var Request = WebRequest.Create(EmailRequest);
Request.Headers.Add("Authorization", "Bearer " + accessToken );
var Response = (HttpWebResponse)Request.GetResponse();
Seems you are trying to get User displayName once the user login into web application.
Its depends how are you getting token, If you are getting token using
Client_Credentialprotocol you wouldn't get displayName using
query parameters like this. You have to use ROPC if you
want to get like this.
You could try following way:
Token And API Request
string tokenUrl = $"https://login.microsoftonline.com/YourTenent/oauth2/token";
var tokenRequest = new HttpRequestMessage(HttpMethod.Post, tokenUrl);
tokenRequest.Content = new FormUrlEncodedContent(new Dictionary<string, string>
{
["grant_type"] = "password",
["client_id"] = "b603c7be-a866_client_id_6921e61f925",
["client_secret"] = "Vxf1SluKb_client_secret_eZ8wL/Yp8ns4sc=",
["resource"] = "https://graph.microsoft.com",
["username"] = "Login_User_Name.onmicrosoft.com",
["password"] = "User_Password"
});
dynamic json;
dynamic results;
HttpClient client = new HttpClient();
var tokenResponse = await client.SendAsync(tokenRequest);
json = await tokenResponse.Content.ReadAsStringAsync();
results = JsonConvert.DeserializeObject<AccessTokenClass>(json);
//New Block For Accessing Data from Microsoft Graph API
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me/?$select=displayName");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", results.access_token);
HttpResponseMessage response = await client.SendAsync(request);
dynamic selectUserDisplayName = JsonConvert.DeserializeObject<dynamic>(await response.Content.ReadAsStringAsync());
Class Used
public class AccessTokenClass
{
public string token_type { get; set; }
public string expires_in { get; set; }
public string resource { get; set; }
public string access_token { get; set; }
public string refresh_token { get; set; }
}
You could refer to this Official Document
Hope this would help you.

POST data using HttpClient

I'm trying to POST a data to web using HttpClient but i can't succeed.
Here is my JSON web api
{
"Categories":[
{
"CategoryID":1,
"Category":"Category 1"
},
{
"CategoryID":2,
"Category":"Category 2"
}
]
}
i'am sending categories data to web my web developer send me above json to send a data from winform to web
Here is my code
IEnumerable<KeyValuePair<string, string>> paramt = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string,string>("CategoryID","1"),
new KeyValuePair<string,string>("Category","Pizza")
};
HttpContent q = new FormUrlEncodedContent(paramt);
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", api);
HttpResponseMessage response = client.PostAsync("api/categories", q).Result;
}
sorry for my english moderator please update my question
Thanks #John with the help of yours i did this
public class CategoryItem
{
public int CategoryID { get; set; }
public string Category { get; set; }
}
public class CategoriesRoot
{
public IList<CategoryItem> Categories { get; set; }
}
var tmp = new CategoriesRoot
{
Categories = new List<CategoryItem> {
new CategoryItem { CategoryID = 1, Category = "Pizza" }
}
};
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", api);
HttpResponseMessage response = client.PostAsJsonAsync("api/categories", tmp).Result;
}

Unsupported Media Type error when posting to Web API

Making a windows phone application and although I may easily pull from my Web Api I am having trouble posting to it. Whenever posting to the api I get the "Unsupported Media Type" error message and I'm not sure as to why it is happening considering the class I using as the base for my JSON post is the same as the one used in the api.
PostQuote (Post Method)
private async void PostQuote(object sender, RoutedEventArgs e)
{
Quotes postquote = new Quotes(){
QuoteId = currentcount,
QuoteText = Quote_Text.Text,
QuoteAuthor = Quote_Author.Text,
TopicId = 1019
};
string json = JsonConvert.SerializeObject(postquote);
if (Quote_Text.Text != "" && Quote_Author.Text != ""){
using (HttpClient hc = new HttpClient())
{
hc.BaseAddress = new Uri("http://rippahquotes.azurewebsites.net/api/QuotesApi");
hc.DefaultRequestHeaders.Accept.Clear();
hc.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await hc.PostAsync(hc.BaseAddress, new StringContent(json));
if (response.IsSuccessStatusCode)
{
Frame.Navigate(typeof(MainPage));
}
else
{
Quote_Text.Text = response.StatusCode.ToString();
//Returning Unsupported Media Type//
}
}
}
}
Quotes and Topic (Model)
public class Quotes
{
public int QuoteId { get; set; }
public int TopicId { get; set; }
public string QuoteText { get; set; }
public string QuoteAuthor { get; set; }
public Topic Topic { get; set; }
public string QuoteEffect { get; set; }
}
//Topic Model//
public class Topic
{
public int TopicId { get; set; }
public string TopicName { get; set; }
public string TopicDescription { get; set; }
public int TopicAmount { get; set; }
}
You should set the media type when creating StringContent
new StringContent(json, Encoding.UTF32, "application/json");
I found this question while working on a quick and dirty reverse proxy. I needed form data and not JSON.
This did the trick for me.
string formData = "Data=SomeQueryString&Foo=Bar";
var result = webClient.PostAsync("http://XXX/api/XXX",
new StringContent(formData, Encoding.UTF8, "application/x-www-form-urlencoded")).Result;
To fix the unsupported media type I had to use HttpRequestMessage and add header to accept json with MediaTypeWithQualityHeaderValue like bellow.
var httpRequestMessage = new HttpRequestMessage
{
Content = new StringContent(json, Encoding.UTF8, "application/json")
};
httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var httpResponse = await _client.PostAsync("/contacts", httpRequestMessage.Content);

Sample code for calling Marketo Rest Api in .net/c# [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
Does anyone have an example of calling a Marketo Rest API from .net/C#.
I am particularly interested in the oauth authentication piece.
http://developers.marketo.com/documentation/rest/authentication/
I plan to call this endpoint
http://developers.marketo.com/documentation/rest/get-multiple-leads-by-list-id/
I cannot find any example out there on the interweb.
I was able to code up a solution for calling a Marketo Rest API and do the OAuth. Below is a how-to
The below code shows the basics, but needs clean up, logging and error handling to be production worthy.
You need to get the Rest api URL's for your Marketo instance. To do this, log into marketo, and navigate to Admin\Integration\Web Services, and use the URLs in the Rest API Section.
You need to get your user id and secret from marketo - navigate to Admin\Integration\Launch Pont. View the details of your Rest Service to get id and secret. If you don't have a Service, then follow these instructions http://developers.marketo.com/documentation/rest/custom-service/.
Finally, you need your list id for the list of leads you want to get. You can get this by navigating to your list and copying the numeric portion of the id out of the url. Example: https://XXXXX.marketo.com/#ST1194B2 —> List ID = 1194
private void GetListLeads()
{
string token = GetToken().Result;
string listID = "XXXX"; // Get from Marketo UI
LeadListResponse leadListResponse = GetListItems(token, listID).Result;
//TODO: do something with your list of leads
}
private async Task<string> GetToken()
{
string clientID = "XXXXXX"; // Get from Marketo UI
string clientSecret = "XXXXXX"; // Get from Marketo UI
string url = String.Format("https://XXXXXX.mktorest.com/identity/oauth/token?grant_type=client_credentials&client_id={0}&client_secret={1}",clientID, clientSecret ); // Get from Marketo UI
var fullUri = new Uri(url, UriKind.Absolute);
TokenResponse tokenResponse = new TokenResponse();
using (var client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(fullUri);
if (response.IsSuccessStatusCode)
{
tokenResponse = await response.Content.ReadAsAsync<TokenResponse>();
}
else
{
if (response.StatusCode == HttpStatusCode.Forbidden)
throw new AuthenticationException("Invalid username/password combination.");
else
throw new ApplicationException("Not able to get token");
}
}
return tokenResponse.access_token;
}
private async Task<LeadListResponse> GetListItems(string token, string listID)
{
string url = String.Format("https://XXXXXX.mktorest.com/rest/v1/list/{0}/leads.json?access_token={1}", listID, token);// Get from Marketo UI
var fullUri = new Uri(url, UriKind.Absolute);
LeadListResponse leadListResponse = new LeadListResponse();
using (var client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(fullUri);
if (response.IsSuccessStatusCode)
{
leadListResponse = await response.Content.ReadAsAsync<LeadListResponse>();
}
else
{
if (response.StatusCode == HttpStatusCode.Forbidden)
throw new AuthenticationException("Invalid username/password combination.");
else
throw new ApplicationException("Not able to get token");
}
}
return leadListResponse;
}
private class TokenResponse
{
public string access_token { get; set; }
public int expires_in { get; set; }
}
private class LeadListResponse
{
public string requestId { get; set; }
public bool success { get; set; }
public string nextPageToken { get; set; }
public Lead[] result { get; set; }
}
private class Lead
{
public int id { get; set; }
public DateTime updatedAt { get; set; }
public string lastName { get; set; }
public string email { get; set; }
public DateTime datecreatedAt { get; set; }
public string firstName { get; set; }
}
Old question, just hoping to help the next guy who ends up here from a google search :-)
This page was probably not there at the time of this post, but there is now a good page with examples in several languages. The page is at
http://developers.marketo.com/documentation/rest/get-multiple-leads-by-list-id
Just in case the link goes dead, here is the code example that they provide for C#
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Samples
{
class LeadsByList
{
private String host = "CHANGE ME"; //host of your marketo instance, https://AAA-BBB-CCC.mktorest.com
private String clientId = "CHANGE ME"; //clientId from admin > Launchpoint
private String clientSecret = "CHANGE ME"; //clientSecret from admin > Launchpoint
public int listId;
public int batchSize;//max 300, default 300
public String[] fields;//array of field names to retrieve
public String nextPageToken;//paging token
/*
public static void Main(String[] args)
{
MultipleLeads leads = new MultipleLeads();
leads.listId = 1001
String result = leads.getData();
Console.WriteLine(result);
while (true)
{
}
}
*/
public String getData()
{
StringBuilder url = new StringBuilder(host + "/rest/v1/list/" + listId + "/leads.json?access_token=" + getToken());
if (fields != null)
{
url.Append("&fields=" + csvString(fields));
}
if (batchSize > 0 && batchSize < 300)
{
url.Append("&batchSize=" + batchSize);
}
if (nextPageToken != null)
{
url.Append("&nextPageToken=" + nextPageToken);
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.ToString());
request.ContentType = "application/json";
request.Accept = "application/json";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
StreamReader reader = new StreamReader(resStream);
return reader.ReadToEnd();
}
private String getToken()
{
String url = host + "/identity/oauth/token?grant_type=client_credentials&client_id=" + clientId + "&client_secret=" + clientSecret;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/json";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
StreamReader reader = new StreamReader(resStream);
String json = reader.ReadToEnd();
//Dictionary<String, Object> dict = JavaScriptSerializer.DeserializeObject(reader.ReadToEnd);
Dictionary<String, String> dict = JsonConvert.DeserializeObject<Dictionary<String, String>>(json);
return dict["access_token"];
}
private String csvString(String[] args)
{
StringBuilder sb = new StringBuilder();
int i = 1;
foreach (String s in args)
{
if (i < args.Length)
{
sb.Append(s + ",");
}
else
{
sb.Append(s);
}
i++;
}
return sb.ToString();
}
}
}
At the time of this response - this page has all of the api calls documented
http://developers.marketo.com/documentation/rest/

Categories

Resources