How to pass ID parameter for GET method without it being directly in the uri - spring-boot

For my school project I'm trying to build an API that allows students to basically CRUD school applications. API is divided into two modules, first one uses IDs directly in uris to access the data like in example below:
#GetMapping("/students/{id}/applications")
public ResponseEntity<List> getStudentApplications(#PathVariable Long id){
Optional<Student> studentById = studentRepo.findById(id);
if(studentById.isPresent()){
return new ResponseEntity<>(studentById.get().getApplications(), HttpStatus.OK);
}
else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
And the second module consumes previous API while not using variables like studentID in uri, because students wont be able to browse other's applications so why include them:
#GetMapping("/my-applications")
public ResponseEntity<List> getApplications(){
return restTemplate.getForEntity("http://localhost:8081/students/{id}/applications", List.class, 1L);
}
My question is how can I pass the id variable to the restTemplate, without it being explicitly in the uri. Example above is obviously hardcoded for the id to be 1

Related

Multiple field resolver resolves same rest API with different query parameters

We are planning to use graphql for orchestrations (For e.g. UI client invokes graphql service which goes to multiple rest endpoint and return the result). Problem here is from one rest endpoint we have to pass different types of query parameters based on the field requested by our client.
We use spring-boot-graphql and graphql-java-tools libraries to initialize graphql
type Query{
user(id: ID): User
}
type User{
phone: [Phone]
address: [Address]
}
type Phone{...}
type Address{...}
My code resolves user field and invoke rest endpoint to fetch phone and address information in a single call like
https:restservice.com\v1\user\123?fields=phone,address
How to resolve two fields expecting data from same rest service. I want something like when client request for phone then i needs to send fields in request parameters as phone alone without address. Can we do that? or is there any other way to define schema to solves this problem?
query {
user(userId : "xyz") {
name
age
weight
friends {
name
}
}
}
Knowing the field selection set can help make DataFetchers more efficient. For example in the above query imagine that the user field is backed by an SQL database system. The data fetcher could look ahead into the field selection set and use different queries because it knows the caller wants friend information as well as user information.
DataFetcher smartUserDF = new DataFetcher() {
#Override
public Object get(DataFetchingEnvironment env) {
String userId = env.getArgument("userId");
DataFetchingFieldSelectionSet selectionSet = env.getSelectionSet();
if (selectionSet.contains("user/*")) {
return getUserAndTheirFriends(userId);
} else {
return getUser(userId);
}
}
};
https://www.graphql-java.com/documentation/v12/fieldselection/

500 Server Error with data transfer in API

public APIController()
{
db = new ApplicationDbContext();
}
ApplicationDbContext db;
[HttpGet]
public List<Category> GetCategories()s
{
return db.Categories.ToList();
}
I am trying to get categories from the Web API. I am using AJAX, but it gives a 500 exception.
Since connection string is right and all setup correctly, There are 2 possible issues in the code I see:
1- Your Api Controller is named APIController which is a reserved word in .NET Api
2- Your get service is trying to return a complete Object from categories which might be related to parent objects and the parent objects are related to other related objects which results in returning the whole database.
I suggest using select new in lambda like this:
[HttpGet]
public List<Category> GetCategories()s
{
return db.Categories.Select(a => new { a.Name, a.ID, a.Description }).ToList();
}
This way you avoid querying the whole database.

Spring REST ResponseEntity how to return response when we have two objects

1. For example UserProfile which has 3 properties name,dob, age
2. And 2nd class let's say UserProfileResponse which has only "id"
public ResponseEntity<UserProfileResponse> createUserProfile(#RequestBody UserProfile userProfile)
{
UserProfileResponse userProfileResponse = new UserProfileResponse();
userProfileResponse.setId(??) // How do I set ID?
**createUserProfileData(userProfile) /// This is used to create DB record**
return new ResponseEntity<UserProfileResponse>(userProfileResponse,HTTPStatus.OK);
}
So for this userProfileResponse.setId(??) how can I set the ID value?
can I directly do like this userProfileResponse.setId(userProfileResponse.getId());
Or I can Pass one more request body like this
ResponseEntity<UserProfileResponse> createUserProfile(#RequestBody UserProfile userProfile, #RequestBody ID)
Thanks in advance.
You can call createUserProfileData method and return the id of the newly inserted object from it.
In createUserProfileData method, you can call saveAndFlush method of the repository which will save the userProfile Object.
This will return the id of the newly inserted object.
Finally your code will look like below:
public ResponseEntity<UserProfileResponse> createUserProfile(#RequestBody UserProfile userProfile)
{
UserProfileResponse userProfileResponse = new UserProfileResponse();
int id = createUserProfileData(userProfile)
userProfileResponse.setId(id)
return new ResponseEntity<UserProfileResponse>(userProfileResponse,HTTPStatus.OK);
}
If you want to get a value from the RequestBody UserProfile which it didn't contain it actually.Sorry it's impossible.
And we only could receive one requestBody at one time,so we need to use some other ways to collect the info.There is some other solutions:
Use #PathVariable to get ID from url
Use #RequestParam to get Id from requestParam
Add a new field named Id into your UserProfile
Use other way that that could get your Id,this depend how you persistent or generate the Id.
In your case,I'm not sure what you are going to do with the id.
If the "createUserProfileData" method means you need to offer an id first for persistence.
Well,I dont know which database and what kind of framework you are using.As I know,most of framework and database has the ability to generate the id automatically.But if you insist to generate id by your self,I recommend you UUID.
If the "createUserProfileData" method is saving the UserProfile to the database literally and the id is generated by the database itself,then you just do it and put the Id represent the record you just saved to UserProfileResponse.
As to how to get the id represent the record you just saved?It's up to the framework you're using and precisely how the code is written.

Manipulate WebAPi POST

I have a WebAPI POST controller like the one below:
[ResponseType(typeof(Product))]
public async Task<IHttpActionResult> PostProduct(Product product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Products.Add(product);
await db.SaveChangesAsync();
return CreatedAtRoute("DefaultApi", new { id = product.Id }, product);
}
To be valid, it expects several values, lets say Name, Price, URL, ManufactureID, StatusID.
However, the POST will not always contain a value for StatusID for example, and therefore the above will fail, as i cannot be null.
But when the value is not sent by the POST, i want to 'intercept' and set the value in code. Let say to int 1.
How would i go about this?
I have been using DTOes for extraxting data from the API, in a nice and viewable way. Can DToes be used in POST also? If so, how? Or any other approach, to setting data, if it does not excist in the POST?
I would say create your Product request model which will be defined in your WebAPI models and there your can define your StatusID as a nullable. After your receive request you can map your Product request data to ProductDto and in that mapping you set your default values if you need them.
Altough you can intercept request on client side and update it but I'm not sure is that something that will work for you.
You should create a POST product class that is agnostic of the persistence. Don't use the generated Product class of your ORM. Using your example above, you should have a ProductModel class that will only contain the properties that the API client can update. Then do the mapping of the DTO to your product data model.
public async Task<IHttpActionResult> PostProduct(ProductModel model)
{
...
var product = db.Products.New();
//mapping here
product.Name = model.Name;
product.Price = model.Price;
}

Receive data in MVC controller from webrole

I understood how to communicate between Web, Worker role and the flow in MVC architecture.
My question is, after I query the data from a table in web role, how can the controller in MVC get this data to diplay in the view?
I tried using a global static variable in webrole, where the data gets populated, but when I access the static variable from the controller, it only returned 'null'. Why am I getting a null?
Thanks.
ok, in case you use the storage client, the implementation would be like:
Create your Model:
public class MyEntity : Microsoft.WindowsAzure.StorageClient.TableServiceEntity
{
public MyEntity()
{
PartitionKey = DateTime.UtcNow.ToString("MMddyyyy");
RowKey = string.Format("{0:10}_{1}",
DateTime.MaxValue.Ticks - DateTime.Now.Ticks, Guid.NewGuid());
}
// Define the properties.
public string Title { get; set; }
public string Name { get; set; }
}
}
2. Define your context class:
public class MyDataContext : TableServiceContext
{
public MyDataContext(string baseAddress,
StorageCredentials credentials)
: base(baseAddress, credentials)
{ }
public IQueryable GetMyEntity
{
get
{
return this.CreateQuery("MyTableName");
}
}
}
Implement your controller action method:
public ActionResult Index()
{
var context = new MyDataContext(storageAccount.TableEndpoint.AbsoluteUri, storageAccount.Credentials);
var results = from g in context.GetMyEntity
where g.PartitionKey ==
DateTime.UtcNow.ToString("MMddyyyy")
select g;
return View(results.FirstOrDefault());
}
this is reference code only, which is very ugly and will hardly work as it is, but it still provides an example of how you can query the table storage in your MVC project.
are we talking about an application whose MVC part is hosted in a worker role and which gets data from a web role which is querying the table storage? Or are we talking about a ASP.NET MVC application here which is hosted in a web role?
static variables is not a good idea at all because of concurrency issues.
in case of scenario 1, how do you communicate with a web role? via web service call directly?
you cold simply call the service from your controller or delegate the call to another layer and then put this data in your model which is then displayed by the corresponding view.
have you tried debugging this application locally using the [azure local dev env][1]
[1]: http://blogs.msdn.com/b/morebits/archive/2010/12/01/using-windows-azure-development-environment-essentials.aspx ? or do you use the real azure infrastructure? Are you sure you are getting the data from your query? maybe the query is wrong? have you observed any exceptions?
we need more information here to be able to help you

Resources