v1.31.0
conocimientoapi-integration-patternstemplates/3921 B

ExternalApiClient.cs.template

Fichero que /hv:api-integration-patterns usa o materializa en el proyecto. Se muestra tal cual está en el plugin.

api-integration-patternsskill
templatescarpeta
3921 Btamaño
2026-09-21último cambio del pack
// TEMPLATE: ExternalApi API Client
// Uso: Customer específico para ExternalApi API (sistema académico Ellucian)

using System.Net.Http.Json;

namespace MyCompany.MyApp.Infrastructure.ApiClients;

public interface IExternalApiClient
{
    Task<StudentDto?> GetStudentAsync(string studentId, CancellationToken ct = default);
    Task<IReadOnlyList<CourseDto>> GetCoursesAsync(string term, CancellationToken ct = default);
    Task<EnrollmentResponseDto> EnrollStudentAsync(EnrollmentRequestDto request, CancellationToken ct = default);
    Task<IReadOnlyList<UniversityDto>> GetUniversitiesAsync(CancellationToken ct = default);
}

public class ExternalApiClient : ApiClientBase, IExternalApiClient
{
    public ExternalApiClient(HttpClient httpClient, ILogger<ExternalApiClient> logger)
        : base(httpClient, logger)
    {
    }

    public async Task<StudentDto?> GetStudentAsync(string studentId, CancellationToken ct = default)
    {
        if (string.IsNullOrWhiteSpace(studentId))
            throw new ArgumentException("Student id is required", nameof(studentId));

        Logger.LogInformation("Obteniendo student {StudentId} desde ExternalApi", studentId);

        var response = await GetAsync<StudentDto>($"students/{studentId}", ct);

        if (response is null)
            Logger.LogWarning("Student {StudentId} not found in ExternalApi", studentId);

        return response;
    }

    public async Task<IReadOnlyList<CourseDto>> GetCoursesAsync(string term, CancellationToken ct = default)
    {
        Logger.LogInformation("Fetching courses for term {Term} from ExternalApi", term);

        var response = await GetAsync<CoursesResponseDto>($"courses?term={term}", ct);

        return response?.Courses ?? new List<CourseDto>();
    }

    public async Task<EnrollmentResponseDto> EnrollStudentAsync(
        EnrollmentRequestDto request,
        CancellationToken ct = default)
    {
        if (request is null)
            throw new ArgumentNullException(nameof(request));

        Logger.LogInformation(
            "Matriculando student {StudentId} en curso {CourseId}",
            request.StudentId,
            request.CourseId);

        var response = await PostAsync<EnrollmentRequestDto, EnrollmentResponseDto>(
            "enrollments",
            request,
            ct);

        if (response is null)
            throw new InvalidOperationException("ExternalApi returned no response for the enrolment");

        Logger.LogInformation(
            "Student {StudentId} matriculado correctamente. Enrollment ID: {EnrollmentId}",
            request.StudentId,
            response.EnrollmentId);

        return response;
    }

    public async Task<IReadOnlyList<UniversityDto>> GetUniversitiesAsync(CancellationToken ct = default)
    {
        Logger.LogInformation("Obteniendo universidades desde ExternalApi");

        var response = await GetAsync<UniversitiesResponseDto>("universities", ct);

        return response?.Universities ?? new List<UniversityDto>();
    }
}

// ============================================================================
// DTOs
// ============================================================================

public record StudentDto(
    string Id,
    string FirstName,
    string LastName,
    string Email,
    string Status);

public record CourseDto(
    string Id,
    string Code,
    string Name,
    int Credits,
    string Term);

public record CoursesResponseDto(List<CourseDto> Courses);

public record EnrollmentRequestDto(
    string StudentId,
    string CourseId,
    string Term);

public record EnrollmentResponseDto(
    string EnrollmentId,
    string StudentId,
    string CourseId,
    DateTime EnrollmentDate,
    string Status);

public record UniversityDto(
    string Id,
    string Name,
    string Country,
    string City);

public record UniversitiesResponseDto(List<UniversityDto> Universities);

← Volver a la ficha de api-integration-patterns