How to expose a Django model as a RESTful web service? - django

I'm trying to create a REST web service that exposes the following Django model:
class Person(models.Model):
uid = models.AutoField(primary_key=True)
name = models.CharField(max_length=40)
latitude = models.CharField(max_length=20)
longitude = models.CharField(max_length=20)
speed = models.CharField(max_length=10)
date = models.DateTimeField(default=datetime.datetime.now)
def __unicode__(self):
return self.name
Here's how I thought about it so far:
Get all Persons
URL: http://localhost/api/persons/
Method: GET
Querystring:
startlat=
endlat=
startlng=
endlng=
Used for getting the Persons that are within the specified coordinate range.
page=
Used for getting the specified page of the response (if the response contains multiple pages).
Returns:
200 OK & JSON
404 Not Found
Example:
Request:
GET http://localhost/api/persons/?startlat=10&endlat=15&startlng=30&endlng=60
Response:
{
"persons":
[
{ "href": "1" },
{ "href": "2" },
{ "href": "3" },
...
{ "href": "100" }
],
"next": "http://localhost/api/persons/?startlat=10&endlat=15&startlng=30&endlng=60&page=2"
}
Get info on a specified Person
URL: http://localhost/api/persons/[id]
Method: GET
Returns:
200 OK & JSON
404 Not Found
Example:
Request:
http://localhost/api/persons/5/
Response:
{
"uid": "5",
"name": "John Smith",
"coordinates": {
"latitude":"14.43432",
"longitude":"56.4322"
},
"speed": "12.6",
"updated": "July 17, 2009, 8:46 a.m."
}
How correct is my attempt so far? Any suggestions are highly appreciated.

{ "href": "1" },
1 is hardly a valid URL. You should use full URLs. Google for HATEOAS.
Also, remember to send a relevant Content-Type header. You may want to make up your own mime-type to describe the format. This gives you the option to later change the content-type (Eg. change the format after publishing). See Versioning REST Web Services

I think query parameters could be simpler and clearer. This would make the URI more readable and would allow more flexibility for future extensions:
GET http://localhost/api/persons/?latitude=10:15&longitude=30:60
You may want to enable these in the future:
GET http://localhost/api/persons/?latitude=10&longitude=60&within=5km

Seems REST-cool. Even i worked on same kind of thing, few days earlier.
The only change, i would love to do in it, is the direct link to the person details. And also some details (like name here) to identify the person, and aid me in decision to navigate further. Like...
{
"persons":
[
{ "name": "John Smith", "href": "http://localhost/api/persons/1/" },
{ "name": "Mark Henry", "href": "http://localhost/api/persons/2/" },
{ "name": "Bruce Wayne", "href": "http://localhost/api/persons/3/" },
...
{ "name": "Karl Lewis", "href": "http://localhost/api/persons/100/" }
],
"next": "http://localhost/api/persons/?startlat=10&endlat=15&startlng=30&endlng=60&page=2"
}
This way, i am giving everything, to present data as,
John
Smith
Mark
Henry
Bruce
Wayne
...
Karl Lewis
Next Page

It's ok to provide shorthand URIs in your JSON responses if you provide some templating system. Like giving a base URI as something like http://whatever.com/persons/{id}/ and then providing IDs. Then with python you can just do a format call on the string. You don't ever want to make the programmer actually look at and understand the meaning of the URIs, which isn't necessary when you use templates.

You might want to take a look at pre-existing REST middleware. I know they saved me a lot of time. I'm using http://code.google.com/p/django-rest-interface/. And a snippet of the urls.py
json_achievement_resource = Collection(
queryset = Achievement.objects.all(),
permitted_methods = ('GET',),
responder = JSONResponder(paginate_by = 10)
)
urlpatterns += patterns('',
url(r'^api/ach(?:ievement)?/(.*?)/json$', json_achievement_resource),
)

Related

searchContacts with phone number query is broken

Using the [searchContacts API method] (https://developers.google.com/people/api/rest/v1/people/searchContacts) used to support searching by telephone number - indeed this is called out in the documentation:
The query matches on a contact's names, nickNames, emailAddresses, phoneNumbers, and organizations fields that are from the CONTACT source.
It no longer returns results when using a phone number as the query. Is this deliberate, or a bug?
As per google people api search by phonenumbers I have tried a query of "canonical format without plus". I have also tried "canonical format with plus" and "exact number as stored".
Name query still works
https://people.googleapis.com/v1/people:searchContacts?readMask=names%2cphoneNumbers&query=Go Ogle&pageSize=30
returns
{
"results": [
{
"person": {
"resourceName": "people/c832768086350305259",
"etag": "%EgcBAgsuNz0/GgECIgwxZGVYd20reHpEUT0=",
"names": [
{
"metadata": {
"primary": true,
"source": {
"type": "CONTACT",
"id": "b8e96298f3117eb"
}
},
"displayName": "Go Ogle",
"familyName": "Ogle",
"givenName": "Go",
"displayNameLastFirst": "Ogle, Go",
"unstructuredName": "Go Ogle"
}
],
"phoneNumbers": [
{
"metadata": {
"primary": true,
"source": {
"type": "CONTACT",
"id": "b8e96298f3117eb"
}
},
"value": "020 7031 3000",
"canonicalForm": "+442070313000"
}
]
}
}
]
}
Phone number query fails
https://people.googleapis.com/v1/people:searchContacts?readMask=names%2cphoneNumbers&query=442070313000&pageSize=30
returns
{}
The query function does indeed seem to be broken at the moment. My tests gave the same results and the question you linked shows that it clearly worked in the past.
I found a bug report on Google's issue tracker. A Googler already replied to it saying that they were able to reproduce it and filed an internal report. It's a matter of time until they fix it so you may want to keep track of that thread or post on it yourself to apply some pressure.
The bug didn't went away although they say it was closed and verified
In order to get the same functionality I had to be creative, the documentation says:
The query matches on a contact's names, nickNames, emailAddresses,
phoneNumbers, and organizations fields that are from the CONTACT
source.
The names, emailAddresses, phoneNumbers and organizations are important fields where you don't want to have garbage, but on my case at least the nickNames had no usage, so I simply add the phone number as nick name and the search works like charm.
Keep in mind that if you have many previous contacts you will have to write a script that will copy their phone number to the one of the nicknames fields.
Enjoy :)

How to get list of meaningful name upon fetching minted NFTs list from Alchemy Api?

I am new to block chain and I am using Alchemy and my NFTs and NFT Meta Data is on "Pinata". When I fetch my minted NFTs from Alchemy API, in response I get list of "contract addresses" and "Token Ids". Is there any way to get list of meaningful names of my minted NFTs instead of ids (without using loops). OR is there a way to store a meaningful name upon minting . Any help will be appreciated.
response upon calling API :
{"balance": "1", "contract": {"address": "0xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}, "id": {"tokenId": "0x0000000000000000000000000000000000000000000000000000000000000000"}}]```
Is there any way to get list of meaningful names of my minted NFTs instead of ids (without using loops).
Yes! As of July 12th, 2022 (current time) -- the getNFTs endpoint includes a withMetadata query param option that defaults to true (see docs).
That means that the response should include the info you might want, including:
title: name of the NFT asset
description: brief human-readable description
media.gateway: public gateway uri for the raw asset
etc.
See full documentation here: https://docs.alchemy.com/alchemy/enhanced-apis/nft-api/getnfts
An example response might look like this:
{
"ownedNfts": [
{
"contract": {
"address": "0x0beed7099af7514ccedf642cfea435731176fb02"
},
"id": {
"tokenId": "28",
"tokenMetadata": {
"tokenType": "ERC721"
}
},
"title": "DuskBreaker #28",
"description": "Breakers have the honor of serving humanity through their work on The Dusk. They are part of a select squad of 10,000 recruits who spend their days exploring a mysterious alien spaceship filled with friends, foes, and otherworldly technology.",
"tokenUri": {
"raw": "https://duskbreakers.gg/api/breakers/28",
"gateway": "https://duskbreakers.gg/api/breakers/28"
},
"media": [
{
"raw": "https://duskbreakers.gg/breaker_images/28.png",
"gateway": "https://duskbreakers.gg/breaker_images/28.png"
}
],
"metadata": {
...
}
},
...
]
...
}
You should then be able to do something like this to get your names:
const names = ownedNfts.map((nft) => nft.title};
Use the getNFTMetadata method to get information on each NFT.

Cannot find the EntityType - SessionEntityType name is composed of Session name and EntityType.display_name

Even though I have provided the correct information in the SessionEntityTypes, the I am getting the following errors. Tried from both REST & Python options, please let me know if there is anything which I am missing in the integrations.
Request
HTTP Method: POST
{
"name": "projects/{projectId}/locations/asia-northeast1/agent/environments/draft/users/-/sessions/c973fe-e44-9b5-34e-b404439b7/entityTypes/speciality_types",
"entities": [
{
"value": "APPLE_KEY",
"synonyms": [
"apple",
"green apple",
"crabapple"
]
},
{
"value": "ORANGE_KEY",
"synonyms": [
"orange"
]
}
],
"entityOverrideMode": "ENTITY_OVERRIDE_MODE_SUPPLEMENT"
}
Response
{
"error": {
"code": 400,
"message": "com.google.apps.framework.request.BadRequestException: Cannot find the EntityType of SessionEntityType 'projects/{projectId}/locations/asia-northeast1/agent/environments/draft/users/-/sessions/c973fe-e44-9b5-34e-b404439b7/entityTypes/speciality_types'. Please note that the SessionEntityType name is composed of Session name and EntityType.display_name.",
"status": "INVALID_ARGUMENT"
}
}
Google Try this API
I am going to paraphrase the issue here in order to ensure I’m not missing any details: you are attempting to create a sessionEntity using the “Try this API” tool, which is the Create (POST) version 2.
The issue is that the “name” you are passing in the request body does not have a valid format for API v2.
The format you are using for the name is:
projects/<ProjectID>/locations/<LocationID>/agent/environments/<EnvironmentID>/users/<UserID>/sessions/<SessionID>/entityTypes/<EntityTypeDisplayName>
Below I’ve listed the two valid name formats for v2 and as you can see the locations/<Location ID> is not needed:
projects/<Project ID>/agent/sessions/<Session ID>/entityTypes/<Entity Type Display Name>
and
projects/<Project ID>/agent/environments/<Environment ID>/users/<User ID>/sessions/<Session ID>/entityTypes/<Entity Type Display Name>
The below request body works as intended, I tested it in the same “Try this API” tool:
{
"name":"projects/{projectId}/agent/environments/draft/users/-/sessions/c973fe-e44-9b5-34e-b404439b7/entityTypes/speciality_types",
"entities":[
{
"value":"APPLE_KEY",
"synonyms":[
"apple",
"green apple",
"crabapple"
]
},
{
"value":"ORANGE_KEY",
"synonyms":[
"orange"
]
}
],
"entityOverrideMode":"ENTITY_OVERRIDE_MODE_SUPPLEMENT"
}

Facebook API process shared object [duplicate]

I just tried through the Graph API Explorer with this path /v2.4/10153513872748291 and I've got this result:
{
"error": {
"message": "(#12) singular links API is deprecated for versions v2.4 and higher",
"type": "OAuthException",
"code": 12
}
}
But https://developers.facebook.com/docs/reference/api/post/ doesn't say anything about deprecation.
I'm not sure if I miss something, or there's another way to get info about an individual post.
Edit: v2.3 works, but v2.4 is the latest one.
Looks like you now need to the combination of the id of the user or page that made the post (or whose wall it is on), an underscore, and then the post id.
For your example post, 10153513872748291, that is made by a page Drama-addict, that has the id 141108613290 – so 141108613290_10153513872748291 will work.
And so does 788239567865981_10153513872748291, because 788239567865981 is the id of the user making the post.
Firstput userId underscore add postId /Likes to check Like status in facebook
userId_post_Id/Likes to fetch Likes Records
userId_post_Id/Comments to fetch Comments Records
https://developers.facebook.com/tools/explorer/145634995501895/?method=GET&path=303261006522998_751199848395776%2FLikes&version=v2.9
**In this link Right side Get Token indide GetAccessToken to select Permission**
303261006522998_751199848395776/Likes
303261006522998_751199848395776/Comments
{
"data": [
{
"id": "124778301449917",
"name": "Manisha Gera"
},
{
"id": "1680577265523548",
"name": "Rubi Sharma"
}
],
"paging": {
"cursors": {
"before": "MTI0Nzc4MzAxNDQ5OTE3",
"after": "MTY4MDU3NzI2NTUyMzU0OAZDZD"
}
}
}

getting high resolution photos that were posted on a page wall/feed

I'm getting my page wall with the open graph.
And when someone posted a photo, I get it on the JSON
{
"id": "27888702146_10150369820322147",
"from": {
"name": "brocoli",
"category": "Record label",
"id": "27888702146"
},
"message": "Vincent Epplay / David Fenech / Jac Berrocal \u00e0 Beaubourg ce soir, 19h, gratos.",
"picture": "http://photos-f.ak.fbcdn.net/hphotos-ak-snc7/305819_10150369820292147_27888702146_8255527_583491475_s.jpg",
"link": "https://www.facebook.com/photo.php?fbid=10150369820292147&set=a.386279807146.165840.27888702146&type=1",
"icon": "http://static.ak.fbcdn.net/rsrc.php/v1/yz/r/StEh3RhPvjk.gif",
"type": "photo",
"object_id": "10150369820292147",
"created_time": "2011-10-16T08:22:21+0000",
"updated_time": "2011-10-16T08:22:21+0000",
"likes": {
"data": [
{
"name": "brocoli",
"category": "Record label",
"id": "27888702146"
},
{
"name": "Agathe Morier",
"id": "601668526"
}
],
"count": 2
},
"comments": {
"count": 0
},
"is_published": true
}
The problem is that the picture link is a low resolution copy of the picture.
How can I get the URL of the full picture ?
Thanks!!
Best
Geoffroy
You can get different version of the photo by querying Graph API with its object_id (not photo post_id which is id in results you provided).
Once you'll request the photo by object id you'll get array of images with URLs and dimensions:
http://graph.facebook.com/10150369820292147?fields=images
If you're attempting to access posts on a Facebook Page (such as for a company) instead of typical user profile, you firstly need to fetch the feed like this:
https://graph.facebook.com/v15.0/YOUR_PAGE_ID_HERE/feed?fields=attachments&access_token=...
And then access data[0].attachments.data[0].subattachments.data[0].target.id to get the object ID (or "target ID" in this case) which you can then use to perform an additional query to obtain the higher resolution image. Increment the numbers to get additional posts and images inside each post.
All you need to do is :
http://graph.facebook.com/me?fields=picture.height(961)
// replace 961 with your required height which u want
You can do this from the main posts list now using
/v2.3/105753476132681/posts?limit=5&fields=likes.summary(true),comments.summary(true), attachments
If attachments doesn't work, try full_picture - but that just gave the 100x100 image for me as well.
Attachments returns a data hash with a 640x480 version of the image at least (not sure what my orig. photo size was)
Use this Code. Its Work for me and get Clear Image
String PICTURE_URL;
String getPicture = hashMap.get("picture");
if (getPicture.contains("_t.")) {
PICTURE_URL = getPicture.replaceAll("_t.", "_n.");
} else if (getPicture.contains("_a.")) {
PICTURE_URL = getPicture.replaceAll("_a.", "_n.");
} else if (getPicture.contains("_s.")) {
PICTURE_URL = getPicture.replaceAll("_s.", "_n.");
} else if (getPicture.contains("_q.")) {
PICTURE_URL = getPicture.replaceAll("_q.", "_n.");
}
url=new URL(PICTURE_URL);
Bitmap bitmap=BitmapFactory.decodeStream(url.openConnection().getInputStream());
((ImageView)view.findViewById(R.id.imageView_FullImage)).setImageBitmap(bitmap);
Though requesting a photo by its object_id will return an array of images with different dimensions, in some cases this approach would require an additional call to the Facebook API.
A simpler approach is to add full_picture to your list of parameters, which will extract the highest resolution image associated with the post.
/v2.2/6275848869/posts?fields=full_picture
For example, if you want to extract all the posts from a Facebook page in the past X days, with the object_id approach you'd need to call the API 3 times:
To get the page info.
To extract the list of posts and obtain the object_id for each post.
For each object_id, to retrieve the list of higher resolution images.