What is the correct way to handle a POST request in Django class based view? - json

In my class based view I am handling a post request (which is an AJAX call).I am inserting some data in a database table and returning some json to the frontend.
def post(self,request,*args,**kwargs):
result_data = {}
doc = kwargs['doc']
doc_obj = Document.objects.get_document(doc)
doc_id = doc_obj.doc_id
reference_obj = Reference.objects.save_to_db(request,doc_id)
friendly_name = reference_obj.friendly_name
result_data['friendly_name'] = friendly_name
return HttpResponse(json.dumps(result_data),content_type='application/json')
My question is that is this the right way of handling a post request?My doubt arises here - I am writing some data into database and returning a json of properties of the same data I have written to the database.
Should I do it differently, ie first storing some data in database and returning just id of the row and again making GET request on the same URL?

I would say if it is an API, it is best to minimize the number of queries by returning the whole object the way you did. In case it is to serve a web user interface, it is simpler to return the id and get the rest of the data, if it needs to be displayed, from the client itself.
Either way is fine. The gain is negligible. I have also seen applications give a local positive feedback and then replace with a negative one if the request was unsuccessful. The technique can improve responsiveness, which is always appreciated.

Django-rest-framework returns the json of the inserted object, so i would think it reasonable to copy that behaviour.

Related

Delete from json without the use of a 'real' id

In Angular:
I'm trying to delete items from a local json server using a http request.
The problem is that the items don't have 'real' id's. Their id's are strings which json doesn't recognises as id's (so far I know).
So when I try to search for an id (either to get it or delete it) I have to use for example:
"http://localhost:3000/watchlist?imdbID=tt5745872"
which gives an array with 1 item.
When using this in a delete request, it will result in a 404.
I was wondering if there is some kind of a workaround for doing this or do I really have to implement 'real' id's?
Context: I'm getting movies from an API and I then store those in an json server. As the API uses string id's, it would be a pain in the ass to try and implement a second id for the same object.

What is the URL when I DELETE an object

I'm running a local server playing around with an API using Django. I have a model called 'Users' populated with a few objects, and am using DefaultRouter.
I want to know what the URL would be if I were to DELETE a specific object from this model. For example, if I wanted to GET a user with an ID of 1 in this model, the URL would be: "localhost:8000/Users/1/". What would the equivalent be to DELETE this user?
I found an explanation of this on the REST API website (below), however, I don't understand what any of the syntaxes means.
What is {prefix}, {url_path}, {lookup} and [.format]? If anyone could provide an example of what this might be using a localhost that would be really helpful.
Thanks
Let us take an example of an API (URL) to update book data with id (pk) being 10. It would look something like this:
URL: http://www.example.com/api/v1/book/10/
Method: PUT/PATCH
With some data associated.
If you want to delete you just need to change method to DELETE instead of put or patch.
Regarding your second question lets compare the url with the parameters.
prefix: http://www.example.com/api/v1/book
lookup: 10
format: It specifies what type of data do you expect when you hit the API. Generally it is considered to be json.
url_path: In general, every thing after look up except query string is considered to be url_path.

What is the least resource intensive to perform "findManyOrCreate" in Laravel eloquent?

I have an array of post codes coming from an input:
$postCodes = collect(["BK13TV", "BK14TV", "BK15TV", "BK16TV"]);
In my database I already have two of the post codes - "BK13TV", "BK16TV".
So I would like to run something like this:
$postCodeModels = PostCode::findManyOrCreate($postCodes->map($postCode) {
return ['code' => $postCode]
})
My initial approach was to load all the post codes, then diff them against the postCodes from the input like so:
PostCode::createMany($postCodes->diff(PostCode::all()->pluck('code')))
However, here it means that I am loading the entire content of post_codes table, which just seems wrong.
In the ideal case, this would return all post code models matching the passed post codes as well as would create entries for post codes that did not exist in the database.
First I need to retrieve existing postcodes:
$existingPostCodes = PostCode::whereIn('code', $postCodes)->get();
The find all the post codes in the input, that are not stored yet in database:
$newPostCodes = $postCodes->diff($existingPostCode->pluck('code'));
Finally retrieve all the new post codes as models:
$postCodeModels = PostCode::whereIn('code', $postCodes)->get();
Admittedly, this still takes three queries, but does eliminate the crazy stuff of loading an entire table worth of data.

Getting the value of a particular cell with AJAX

My goal is very simple and I would guess it is a very common goal among web developers.
I am creating a Rails (5.1) application, and I simply want to use AJAX to get the value of a specific cell in a specific row of a specific table in my database (later I am going to use that value to highlight some text on the current page in the user's browser).
I have not been able to find any documentation online explaining how to do this. As I said, it seems like a basic task to ask of jquery and ajax, so I'm confused as to why I'm having so much trouble figuring it out.
For concreteness, say I have a table called 'animals', and I want to get the value of the column 'species' for the animal with 'id' = 99.
How can I construct an AJAX call to query the database for the value of 'species' for the 'animal' with 'id' = 99 .
Though some DBs provide a REST API, what we commonly do is define a route in the app to pull and return data from the DB.
So:
Add a route
Add a controller/action for that route
In that action, fetch the data from the DB and render it in your preferred format
On the client-side, make the AJAX call to that controller/action and do something with the response.

Valid to return different json-response depending on list or retrieve?

I am currently designing a Rest API and is a little stuck on performance matters for 2 of the use cases in the system:
List all campaigns (api/campaigns) - needs to return campaign data needed for listing and paging campaigns. Maybe return up to 1000 records and would take ages to retreive and return detailed data. The needed data can be returned in a single DB call.
Retrieve campaign item (api/campaigns/id) - need to return all data about the campaign and may take up to a second to run. Multiple DB calls is needed to get all campaign data for a single campaign.
My question is: Is it valid to return different json-responses to those 2 calls (if well documented) even if it regards the same resource? I am thinking that the list response is a sub set of the retreive-response. The reason for this is to make to save DB calls and bandwitdh + parsing.
Thanks in advance!
I think it's both fine and expected for /campaigns and /campaigns/{id} to return different information. I would suggest using query parameters to limit the amount of information you need to return. For instance, only return a URI to each player unless you see a ?expand=players query parameter, in which case you return detailed player information.