Search code examples
c#curlhttpclientlob

How to receive and show LOB.com postcard cURL/API requests in C# with webRequest Class


I am trying to get postcard information from LOB.com account using CURL.

lob.com they are providing:

curl https://api.lob.com/v1/postcards/psc_5c002b86ce47537a \
  -u test_0dc8d51e0acffcb1880e0f19c79b2f5b0cc:

How can I get the json response using this CURL?

I've used

var httpWebRequest = (HttpWebRequest) WebRequest.Create("https://api.lob.com/v1/postcards/psc_95d1eafeb5b9a766");

httpWebRequest.ContentType = "application/json";

httpWebRequest.Accept = "*/*";

httpWebRequest.Method = "GET";

httpWebRequest.Headers.Add("Authorization", "test_48d2bbf75c2edc75155c401d119bfae5526:");

var httpResponse = (HttpWebResponse) httpWebRequest.GetResponse();

using(var streamReader = new StreamReader(httpResponse.GetResponseStream())) {
 gta_allCustomersResponse answer = JsonConvert.DeserializeObject < gta_allCustomersResponse > (streamReader.ReadToEnd());
 return answer;

Above code showing 422 (Unprocessable entity) or 400 (Bad request) error if I run this code.


Solution

  • I recommend using RestSharp to send simple HTTP requests to Lob.

    Or you can make it using HttpClient:

    public static void Main()
    {
        string API_KEY = "YourApiKey";
    
        HttpClient httpClient = new HttpClient();
        var authHeaderBytes = Encoding.ASCII.GetBytes(API_KEY + ":");
        httpClient.DefaultRequestHeaders.Authorization = 
            new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(authHeaderBytes));
    
        var requestPayload = new Dictionary<string, string>
        {
            { "name", "John Doe" },
            { "address_line1", "123 Main St" },
            { "address_city", "San Francisco" },
            { "address_state", "CA" },
            { "address_zip", "94107" },
            { "address_country", "US" }
        };
    
        var encodedRequestForm = new FormUrlEncodedContent(requestPayload);
        var APIResponse = httpClient.PostAsync("https://api.lob.com/v1/addresses", encodedRequestForm).GetAwaiter().GetResult();
        var addressString = APIResponse.Content.ReadAsStringAsync().GetAwaiter().GetResult();
    
        System.Console.WriteLine(addressString);
    }
    

    This example is for an address, you can develop same for postcards, just review the curl request or Java request from the documentation and code accordingly.

    Hope this helps!