.net 에서 외부 API호출을 하는 클라이언트 객체가 필요할시 기본제공되는 WebClient 만으로 충분하게 사용할수 있지만 Flurl을 이용하면 더 유연하고 테스트가능한 형태로 API Client를 구현할수 있습니다. ( unit testing with the functionality ) url : |
// Flurl will use 1 HttpClient instance per host
var person = await "https://api.com"
.AppendPathSegment("person")
.SetQueryParams(new { a = 1, b = 2 })
.WithOAuthBearerToken("my_oauth_token")
.PostJsonAsync(new
{
first_name = "Claire",
last_name = "Underwood"
})
.ReceiveJson<Person>(); |
// fake & record all http calls in the test subject
using (var httpTest = new HttpTest()) {
// arrange
httpTest.RespondWith(200, "OK");
// act
await sut.CreatePersonAsync();
// assert
httpTest.ShouldHaveCalled("https://api.com/*")
.WithVerb(HttpMethod.Post)
.WithContentType("application/json");
} |
호출해야하는 API의 URL의 인자값이 복잡할시 이것을 문자열 결합으로만 만들게 되면 가독성이 안좋아지고 실수할 가능성이 높습니다.
특히나 인자값중 특수문자가 URLEncode처리되면 호출 URL 문자열을 눈 으로 검증하기는 더욱더 어려워 집니다.
Flurl을 사용하면 함수형 방식으로 Safe하고 유연한 URL Builder가 가능하며, 간편하게 Json 호출결과물을 Object로 변환가능합니다.
유닛테스트는 보너스입니다.
try {
await url.PostJsonAsync(poco);
}
catch (FlurlHttpTimeoutException) {
// FlurlHttpTimeoutException derives from FlurlHttpException; catch here only
// if you want to handle timeouts as a special case
LogError("Request timed out.");
}
catch (FlurlHttpException ex) {
// ex.Message contains rich details, inclulding the URL, verb, response status,
// and request and response bodies (if available)
LogError(ex.Message);
} |
url.AllowHttpStatus(HttpStatusCode.NotFound, HttpStatusCode.Conflict).GetAsync();
url.AllowHttpStatus("400-404,6xx").GetAsync();
url.AllowAnyHttpStatus().GetAsync(); |
Http의 Status 에러코드는 정상적인 네트워크 반환입니다. 하지만 이것을 호출하는 입장에서 그것이 허용하는 결과치일수도 있고
아닐수도 있습니다. 이것은 Status에대한 예외범위를 클라이트쪽에서 결정할수 있고 예외 프로그래밍 설계를할수 있다란 의미입니다.
.