Parse FHIR Patient response to json - c#

I'm new to .Net and FHIR. I followed a few tutorial to understand how FHIR API works. I need to create an application that use only GET request to get data from server. Below, I am trying to make a request to retrieve a patient by ID in PatientRepository class. However, when I test it with Postman, it doesn't return any response. How should I change my code? Many thanks
Model:
public class Patient : Hl7.Fhir.Model.Patient
{
public string name { get; set; }
public string birthday { get; set; }
}
public class PatientList
{
public List<Patient> Patients { get; set; }
}
Controller:
public class PatientController : Controller
{
private readonly IPatientRepository _patientRepository;
public PatientController(IPatientRepository patientRepository)
{
_patientRepository = patientRepository;
}
[HttpGet]
[Route("api/GetPatientById/{id}")]
public IActionResult getPatientById(long id)
{
var model = _patientRepository.GetPatientById(id);
if (model == null)
return NotFound();
return Ok(model);
}
}
}
PatientRepository:
public class PatientRepository : IPatientRepository
{
public async Task<Patient> GetPatientById(long id)
{
var client = new FhirClient("https://fhir.****.***/hapi-fhir-jpaserver/fhir/");
client.Timeout = (60 * 100);
client.PreferredFormat = ResourceFormat.Json;
var pat = client.Read<Patient>("Patient/1");
var parser = new FhirJsonParser();
return new Patient
{
birthday = pat.birthday,
}
}
}

Related

Received Model is empty in the controler after post

I have one API in my webservice App that receives an empty model after the post.
This is the code in my testclient that calls the API
private async void AddDriverPayment()
{
ModelPalmDriverPaymentRequest modelPalmDriverPaymentRequest = new ModelPalmDriverPaymentRequest()
{
SCS_ID = int.Parse(gttDXTextEditAddDriverPaymentSCS_ID.Text),
DriverID = int.Parse(gttDXTextEditAddDriverPaymentDriverID.Text),
Amount = decimal.Parse(gttDXTextEditAddDriverPaymentAmount.Text),
Remark = gttDXTextEditAddDriverPaymentRemark.Text,
PaymentType = gttDXTextEditAddDriverPaymentPaymentType.Text,
PaymentYear = int.Parse(gttDXTextEditAddDriverPaymentPaymentYear.Text),
PaymentWeek = int.Parse(gttDXTextEditAddDriverPaymentPaymentWeek.Text),
DocumentPath = gttDXTextEditAddDriverPaymentDocumentPath.Text,
DatePayment = dateTimePickerAddDriverPayment.Value
};
string JsonData = JsonConvert.SerializeObject(modelPalmDriverPaymentRequest);
System.Net.Http.StringContent restContent = new StringContent(JsonData, Encoding.UTF8, "application/json");
HttpClient client = new HttpClient();
try
{
var response = await client.PostAsync(comboBoxEditPalmAddDriverPayment.Text, restContent);
if (response.IsSuccessStatusCode)
{
var stream = await response.Content.ReadAsStringAsync();
ModelPalmDriverPaymentResponse Result = JsonConvert.DeserializeObject<ModelPalmDriverPaymentResponse>(stream);
textBoxAddDriverPaymentResult.Text = Result.SCS_ID.ToString() + " " + Result.PaymentID.ToString();
}
else
{
textBoxAddDriverPaymentResult.Text = response.StatusCode + " " + response.ReasonPhrase;
}
}
catch (Exception ex)
{
textBoxAddDriverPaymentResult.Text = ex.Message;
}
}
And this is the controller code in the webservice
[Route("palm/AddDriverPayment")]
[ApiController]
public class ControllerPalmDriverPayment : ControllerBase
{
private readonly RepositoryPalmDriverPayment _repositoryPalmDriverPayment = new();
[HttpPost]
public IActionResult AddDriverPayment(ModelPalmDriverPaymentRequest modelPalmDriverPaymentRequest)
{
try
{
return base.Ok(_repositoryPalmDriverPayment.AddDriverPaymemnt(modelPalmDriverPaymentRequest));
}
catch (System.Exception)
{
return base.BadRequest("Nope not working...");
}
}
}
The model looks like this (I copied the model class from the service into the client, so I am sure they are exact the same)
public class ModelPalmDriverPaymentRequest
{
public int SCS_ID;
public int DriverID;
public decimal Amount;
public string? Remark;
public string? PaymentType;
public int PaymentYear;
public int PaymentWeek;
public string? DocumentPath;
public DateTime DatePayment;
}
When I try the code, I can see in debug of the testclient that when I post the data, the model is correct filled,
but then I can see in debug on the webservice that the received model is empty
I have other API's in this webservice that I test with the same client, they all do not have this problem.
I found this question but the answers don't help me
Anybody has any idea what the problem here is ?
EDIT
I found the problem, and wrote it in an answer so anybody with the same problem can find it.
Specify Content-Type: application/json on the client side or use the [FromBody] attribute on your ModelPalmDriverPayemntRequest parameter on the controller method.
More details about FromBody attribute here
I have it working now, the problem was I forgot to provide getters and setters in the model
So once I changed this
public class ModelPalmDriverPaymentRequest
{
public int SCS_ID;
public int DriverID;
public decimal Amount;
public string? Remark;
public string? PaymentType;
public int PaymentYear;
public int PaymentWeek;
public string? DocumentPath;
public DateTime DatePayment;
}
into this
public class ModelPalmDriverPaymentRequest
{
public int SCS_ID { get; set; }
public int DriverID { get; set; }
public decimal Amount { get; set; }
public string Remark { get; set; }
public string PaymentType { get; set; }
public int PaymentYear { get; set; }
public int PaymentWeek { get; set; }
public string DocumentPath { get; set; }
public DateTime DatePayment { get; set; }
}
It worked again

Swagger API wont allow me to post multiple IFormFIles

Controller:
[HttpPost("CreateEmail")]
[Consumes("multipart/form-data")]
public async Task<ApiResponse<Guid>> PostEmailToProcess([FromForm]EmailToProcess email)
{
try
{
var emailToAdd = new EmailToProcessDto(email);
emailToAdd.Created = DateTime.Now;
var emailId = await _emailRepository.PostEmailAsync(emailToAdd);
foreach (var file in email)
{
if (email.IFormFile != null)
{
await _contentUploadService.Upload(file, emailId.Data);
}
}
etc
EmailToProcess Object:
{
public class EmailToProcess
{
public string From { get; set; }
public string To { get; set; }
...
public List<IFormFile> IFormFile { get; set; }
}
}
As you can see in the image, swagger is only letting me submit 1 FormFile. I am new to swagger and creating APIs so Im sure Im missing something small.

RestSharp fails on saving results

Response is successful, i can view it in Visual Studio, but when i try to get returned data, its null.
This is API https://yoda-api.appspot.com/api/v1/yodish?text=I%20am%20yoda
And this is my code:
public class YodishModel
{
public string yodish { get; set; }
}
public class YodishResult
{
public YodishModel Result { get; set; }
}
public class YodishService : iService
{
public string GetText(string text)
{
Lazy<RestClient> client = new Lazy<RestClient>(() => new RestClient($"http://yoda-api.appspot.com/api/v1/yodish?text={text}"));
var request = new RestRequest();
var response = client.Value.Execute<YodishResult>(request);
if (response.IsSuccessful)
{
return response.Data.Result.yodish;
}
return null;
}
public string ToUrl(string text)
{
return HttpUtility.UrlEncode(text);
}
}
Response is successful, i can view the result, but Result is null (NullPointerException).
Also, is there a way to use parameters here instead of using string interpolation? 'text' is part of the URL which is officially not a paremeter.
In your case, you were deserializing using a mismatched object. This is what I did to fix it:
public class YodishModel
{
public string yodish { get; set; }
}
public class YodishService
{
public string GetText(string text)
{
Lazy<RestClient> client = new Lazy<RestClient>(() => new RestClient($"https://yoda-api.appspot.com/api/v1/"));
var request = new RestRequest($"yodish").AddQueryParameter("text", Uri.EscapeDataString(text), true);
var response = client.Value.Execute<YodishModel>(request);
if (response.IsSuccessful)
{
return Uri.UnescapeDataString(response.Data.yodish);
}
return null;
}
}
I also added the AddQueryParameter, as you mentioned.

WEB API post from uri/ Query string in post

i have a model
public partial class TalentVendorShots
{
public int Id { get; set; }
public string Email { get; set; }
public string One { get; set; }
public string Two { get; set; }
public string Three { get; set; }
public string Four { get; set; }
public string Five { get; set; }
public string Six { get; set; }
public string Seven { get; set; }
public string Eight { get; set; }
public string Nine { get; set; }
public string Ten { get; set; }
}
and basic controllers
[Route("api/[controller]")]
[ApiController]
public class TalentVendorShotsController : ControllerBase
{
private readonly champagneDatabase _context;
public TalentVendorShotsController(champagneDatabase context)
{
_context = context;
}
// GET: api/TalentVendorShots
[HttpGet]
public async Task<ActionResult<IEnumerable<TalentVendorShots>>> GetTalentVendorShots()
{
return await _context.TalentVendorShots.ToListAsync();
}
// GET: api/TalentVendorShots/5
[HttpGet("{id}")]
public async Task<ActionResult<TalentVendorShots>> GetTalentVendorShots(int id)
{
var talentVendorShots = await _context.TalentVendorShots.FindAsync(id);
if (talentVendorShots == null)
{
return NotFound();
}
return talentVendorShots;
}
// PUT: api/TalentVendorShots/5
[HttpPut("{id}")]
public async Task<IActionResult> PutTalentVendorShots(int id, TalentVendorShots talentVendorShots)
{
if (id != talentVendorShots.Id)
{
return BadRequest();
}
_context.Entry(talentVendorShots).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!TalentVendorShotsExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/TalentVendorShots
[HttpPost]
public async Task<ActionResult<TalentVendorShots>> PostTalentVendorShots(TalentVendorShots talentVendorShots)
{
_context.TalentVendorShots.Add(talentVendorShots);
await _context.SaveChangesAsync();
return CreatedAtAction("GetTalentVendorShots", new { id = talentVendorShots.Id }, talentVendorShots);
}
// DELETE: api/TalentVendorShots/5
[HttpDelete("{id}")]
public async Task<ActionResult<TalentVendorShots>> DeleteTalentVendorShots(int id)
{
var talentVendorShots = await _context.TalentVendorShots.FindAsync(id);
if (talentVendorShots == null)
{
return NotFound();
}
_context.TalentVendorShots.Remove(talentVendorShots);
await _context.SaveChangesAsync();
return talentVendorShots;
}
private bool TalentVendorShotsExists(int id)
{
return _context.TalentVendorShots.Any(e => e.Id == id);
}
}
}
all of this works fine. i get information from the database fine. now i want to make a post to the table via uri. no body.for example
/api/TalentVendorShots/id=1,email=testemail should create a new record with id of 1 and email of testemail. how can i accomplish this?
The basic rule is, You should use POST if the action is not idempotent. Though you can pass the query parameters and no body to POST. But It would not make sense in this scenario. Basically query parameters are used to get/filter information.
Similar way many Web API testing tools like ARC, Swagger, and PostMan (chrome extension does not allow, but standalone application allows) does not allow to send body with the GET request. Though you can send the body in GET requests.

Modify value before I display it in the view?

I have a feeds table
Id Message Created
1 aaa 2016-02-25 12:18:51
2 bbb 2016-02-24 12:18:51
3 ccc 2015-02-25 12:18:51
I can get all the values like this
public ActionResult Index()
{
using (var db = new ApplicationDbContext())
{
var feeds = db.Feeds.ToList();
return View(feeds);
}
}
I have created a class that change date from datetime to e.g "1 day ago". And this works fine
var myTime = DateExtension.TimeAgo(DateTime.Parse("2016-02-25 12:18:51"));
I want to modify all the dates in feed with help of DateExtension.TimeAgo before I return in to the view. How can I do that?
try this:
return View(
feeds.Select(x=>
new Feed{
Id=x.Id,
Message=x.Message,
Created=DateExtension.TimeAgo(DateTime.Parse(x.Created))
}).toList());
where Feed your class, with the same fields
Use FeedDisplayModel class in your view
public class Class1TestController
{
public ActionResult Index()
{
using (var db = new ApplicationDbContext())
{
var feeds = db.Feeds.Select(itm=>new FeedDisplayModel(itm)).ToList();
return View(feeds);
}
}
}
class Feed
{
public DateTime Created { get; set; }
public int Id { get; set;}
public string Message { get; set;}
}
class FeedDisplayModel : Feed
{
public string Ago { get { return Created.TimeAgo(); } }
public FeedDisplayModel(Feed itm){
this.Created=itm.Created;
this.Id=itm.Id;
this.Message=itm.Message;
}
}
public static class DateExtension
{
public static string TimeAgo(this DateTime dt)
{
return "your implementation of ";
}
}

Categories

Resources