I am moving from SQL to Couch DB from my web application, my very first application.
While i can not say why I do not like SQL queries, not sure that i don not, the idea of making CURL requests to access my database sound must better than using PHPs PDO .
I have spent a little over a day and a half trying to acquaint myself with the couch DB HTTP API. I can not claim I have throughly read the API , but who thoroughly reads an API before beginning to code. So my, possibly silly, question is - how do I pass an variable other than doc to a map function while making a http request to the view. The API clearly says that a map function only takes a single parameter which is "doc", in which case the function below itself is wrong but I can't find any section in the API that lets me query a database using end-user provided input.
my map function is
function(doc, pid2){
if (doc.pid === pid2)
{
emit(doc._id, doc) ;
}
}
pid2 is a number that will be provided by a front end user.
<?php
$pid2 = file_get_contents(facebook graphi api call_returns a Profile ID) ;
$user_exists = HTTP request to couch DB view to return
in JSON format the list of JSON documents with pid = $pid2
?>
Let your view emit the documents with doc.pid as the key
function(doc) {
emit(doc.pid, doc);
}
and use the key parameter to retrieve the right document:
http://localhost:5984/<database>/_design/<designdoc>/_view/<viewname>?key=<pid2>
This should return all documents with doc.pid === pid2.
Related
Selecting a value and right-clicking enables me to save it as a Global variable.
But there is no option to save it as a collection variable.
In the environments section as well. I can see Globals but my collection is not available.
But as I go through blogs/ articles online I can see some variables that are scoped to a collection.
Can I know a way to achieve this?
Tests tab is all you need
Considering the Stackoverflow GetUser API for Reference.
NOTE: The below-shown response is a part of the original response.
Response:
{
"items": [
{
"user_type": "registered",
"user_id": 12345678,
}
]
}
In the above response let's say we need user_type, and user_id in another API's URL / body / headers.
Before accessing we need to store these variables after receiving the response. This can be done in the Tests tab in postman request.
const jsonData = JSON.parse(responseBody);
const userType = jsonData?.items?.[0]?.user_type;
const userId = jsonData?.items?.[0]?.user_id;
if(userType){
pm.collectionVariables.set("userType",userType)
}
if(userId){
pm.collectionVariables.set("userId", userId)
}
Points to Note:
Postman tests are written in Javascript.
Optional chaining in line 2,3 is to avoid console errors. Possible Scenario: When API fails and returns an error response.
The IF Statements are to avoid null values in case of an Error Response. If statements are not mandatory. In fact without using if statements you will get to know clearly that something went wrong.
How to use collection variables
Once you make a request with the above tests. Postman IntelliSense suggests available collection variables. ( Refer to the image attached )
We are sending the body as a raw JSON in this Test Endpoint. Note that userType is surrounded by double quotes "" whereas userId is not. ( JSON syntax )
I've got a PATCH request that looks like this:
{{host}}/api/invoice/12345678/withdraw
host is a variable determining the environment.
For this request I need to add a unique authorization token.
The problem is I need to send dozens of such requests. Two things change for each request:
id of invoice (for this case is '12345678')
auth token (herebetoken1).
How can I automate it?
You can use Postman Runner for your problem. In Runner, you can send specified requests in specified iterations and delay with data (json or csv file).
For more info, I suggest you take a look at the links below.
Importing Data Files in Postman
Using CSV and JSON Data Files
Request:
Runner:
Data: (You can choose one of them)
Json Data: (data.json)
csv Data: (data.csv)
Preview Data in Runner:
Result:
use the below pre-request script , and call replace id in url and auth in authorization with {{id}} and {{token}} variables . Use collection runner to execute it .
Replace the hashmap with what you requires
hashmap = {
"1234": "authtoken1",
"2222": "authtoken2"
}
pm.variables.get("count") === undefined ? pm.variables.set("count", 0) : null
let keyval = Object.entries(hashmap)
let count = pm.variables.get("count")
if (count < keyval.length) {
pm.variables.set("id", keyval[pm.variables.get("count")][0])
pm.variables.set("token", keyval[pm.variables.get("count")][1])
pm.variables.set("count", ++count)
keyval.length===count? null:postman.setNextRequest(pm.info.requestName)
}
Example collection:
https://www.getpostman.com/collections/43deac65a6de60ac46b3 , click inport and import by link
im using CodeIgniter 1.7 framework to make my Website.
Another team do the mobile version for iPhone.
So the other team ask me to do a web service for authentification.
They tell that they will send me :
POST REQUEST
Input : login , password, push_token
if failure authentification -> Output HTTP : error code 0
if success -> Output XML :
<DATA>
<User id='id_user' title='..' first_name='' last_name='' email='' postal='' country_id=''/>
</DATA>
Basically i have this function for authentification:
function check_login($username="", $password="")
{
$username = $_POST['username'];
$password = $_POST['password'];
...
...
}
im looking into this post Codeigniter web services but i don't understand how its really work because im new in webservice.
I would consider using json as a sole output with one value being TRUE or FALSE depending on success. It's easier to handle, and all it requires is for your site to be in utf8.
If your check_login() returns TRUE, use that as the condition for success.
Example of reply:
/* Class etc. */
function do_login() {
$arr_json = array('success' => FALSE);
if ($this->login_library->check_login()) {
$arr_json['success'] = TRUE;
$arr_json['user_id'] = $this->login_library->user_id;
}
echo json_encode($arr_json);
}
login_library is just an example for your library which does the login. The reply they receive only needs to be decoded through json_decode(). And then simply check if the key success is TRUE or not.
If needed, have an extra key called error_message or similiar, and you can run all post-values through form_validation. Then you can also have $arr_json['error_message'] = trim(validation_errors('', "\n")); before the echo aswell.
You should definately look into Phil Sturgeons CodeIgniter Rest Server:
https://github.com/philsturgeon/codeigniter-restserver
There's a pretty good documentation. He also made a screencast about it: http://philsturgeon.co.uk/blog/2011/03/video-set-up-a-rest-api-with-codeigniter
Furthermore you could have a look at this article, where Adam Whitney explains his approach:
Building a RESTful Service using CodeIgniter
http://adamwhitney.net/blog/?p=707
e.g.
FB.api('/me/permissions="user_photos"', function (response) { });
instead of
FB.api({ method: 'fql.query', query: 'SELECT user_photos FROM permissions WHERE uid=me()' }, function(resp) {
for(var key in resp[0]) {
if(resp[0][key] === "1")
console.log(key+' is granted')
else
console.log(key+' is not granted')
}
});
Yes, Theres a way called selection in graph api or more advance field expansion:
You can choose the fields (or connections) you want returned with the "fields" query parameter, Example:
FB.api('/me/permissions?fields=user_photos', function (response) { });
Graph API Explorer Demo
EDIT:
Quoted directly from graph api doc:
Selection
By default, most object properties are returned when you make a query.
You can choose the fields (or connections) you want returned with the
"fields" query parameter. For example, this URL will only return the
id, name, and picture of Ben:
https://graph.facebook.com/bgolub?fields=id,name,picture
You can also request multiple objects in a single query using the
"ids" query parameter. For example, the URL
https://graph.facebook.com?ids=arjun,vernal returns both profiles in
the same response.
The "ids" query parameter also accepts URLs. This is useful for
finding IDs of URLs in the Open Graph. For example:
https://graph.facebook.com/?ids=http://www.imdb.com/title/tt0117500/
Additionally, there is a special identifier me which refers to the
current user. So the URL https://graph.facebook.com/me returns the
active user's profile.
When retrieving Posts via the /home, /feed, or /posts connection, you
can restrict the results to only those with a location attached by
adding with=location to the URL parameters:
https://graph.facebook.com/me/home?with=location
Source: Graph API Docs
I'm trying to do integration with Salesforce using their REST API and CF8.
I got the OAuth bit working, getting data etc but now I'm trying to update some records in Contact table.
First I tought about doing it the "proper" way as their docs say -
Update a record using HTTP PATCH.
But CFHTTP doesn't support PATCH method.
So then I tried running a SOQL query:
UPDATE Contact SET MailingStreet = 'Blah Blah' WHERE Id = '003A000000Zp4ObIAJ'
but here I'm getting
{"message":"unexpected token: UPDATE","errorCode":"MALFORMED_QUERY"}
Does anyone have an idea how to do it?
You can create your own PATCH method if your client supports it, but there is an easier way. From the Force.com REST API Developer's Guide:
If you use an HTTP library that doesn't allow overriding or setting an
arbitrary HTTP method name, you can send a POST request and provide an
override to the HTTP method via the query string parameter
_HttpMethod. In the PATCH example, you can replace the PostMethod line
with one that doesn't use override:
PostMethod m = new PostMethod(url + "?_HttpMethod=PATCH");
In CF9 CFScript, using the method that Paddyslacker already suggested for adding _HttpMethod=PATCH to the URL:
private boolean function patchObject(required string sfid, required string type, required struct obj) {
local.url = variables.salesforceInstance & '/services/data/v' & variables.apiVersion &'/sobjects/' & arguments.type & '/' & arguments.sfid &'?_HttpMethod=PATCH';
local.http = new Http(url=local.url,method='post');
//... convert obj to a json string, add to local.http ...
local.httpSendResult = local.http.send().getPrefix();
}
We have a CF9 CFC that we wrote that wraps most of the REST API that we will be open sourcing soon. I'll come back and link to it when we do.