Reputation: 1129
I have this code in my website which i'm trying to do a POST request to this api called schooltime https://schooltimeapp.docs.apiary.io/#introduction/requirements-for-apps-using-the-schooltime-api. Currently i'm trying to post 4 values from my textbox into the REST api but i am currently having some trouble on going about it as it is my first time using C# to connect to an API.
Any help would be greatly appreciated thanks!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Web.Script.Serialization;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
private const string URL = "https://school-time.co/app2/index.php/api/students/";
private string urlParameters = "StRest@123";
protected void Page_Load(object sender, EventArgs e)
{
}
public class Result
{
public string id { get; set; }
public string name { get; set; }
public string email { get; set; }
public string message { get; set; }
}
protected void Button_Add_Click(object sender, EventArgs e)
{
string name = TextBox_Name.Text;
string pass = TextBox_Pass.Text;
string email = TextBox_Email.Text;
string birthdate = TextBox_Birth.Text;
var webRequest = (HttpWebRequest)WebRequest.Create("https://school-time.co/app2/index.php/api/students/");
var webResponse = (HttpWebResponse)webRequest.GetResponse(); if (webResponse.StatusCode == HttpStatusCode.OK)
{
}
else Label1.Text = "Invalid Response";
}
}
Upvotes: 1
Views: 494
Reputation: 727
You could use a client like RestSharp, then use Postman to generate the code in C#.
With your current setup, something like this within your Button_Add_Click
may work (I have not tested it):
var webRequest = (HttpWebRequest)WebRequest.Create("https://school-time.co/app2/index.php/api/students/");
var postData = "name=hello";
postData += "&email [email protected]";
//add other attributes...
var data = Encoding.ASCII.GetBytes(postData);
webRequest.Method = "POST";
webRequest.Headers.Add("ST-API-KEY", "StRest@123");
webRequest.ContentType = "application/json";
using (var stream = webRequest.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)webRequest.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
}
Upvotes: 1