Fetch Status Code from restful webservice - rest

I am not able to just fetch the status code from a restful webservice. The web service is just responding with 201 or 401. I am pretty new to react native and I just stuck for hours now.
I am calling the this function in another component. The response I am receiving is always LOG {"_40": 0, "_55": null, "_65": 0, "_72": null}
export default class forgotPasswordCall extends Component {
_forgotPassword = async (username, email) => {
let bodyData = {
'username': username,
'email': email,
}
try {
const response = await fetch('webserviceURL', {
method: "POST",
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify(bodyData)
})
return response.status;
}
catch (error) {
console.error(error);
}
}
}
I would need to receive the status code itself.

I would highly recommend using axios instead of fetch. You should try it !

Related

Connecting to WhatsApp API using axios.post using TypeScript

I just started using the WhatsApp Cloud API.
I took the example that was provided on glitch as a reference but there are things that are different since I'm taking the serverless approach.
As seen in glitch's example, it used axios(config) method and I tried it out and it worked fine after minor changes but when I tried axios.post() method I keep on getting the following error:
AxiosError: Request failed with status code 400
The axios(config) method (Which works)
await axios({
method: "POST", // Required, HTTP method, a string, e.g. POST, GET
url:"https://graph.facebook.com/{{Version}}/{{Phone-Number-ID}}/messages?access_token={{Token}}",
data: {
messaging_product: "whatsapp",
recipient_type: "individual",
to: {{Recipient-Phone-Number}},
text: {body: "Welcome back"},
},
headers: {"Content-Type": "application/json"},
});
The axios.post() method (Which doesn't works)
let url = "https://graph.facebook.com/{{Version}}/{{Phone-Number-ID}}/messages"
let payload = {
messaging_product: "whatsapp",
recipient_type: "individual",
to: {{Recipient-Phone-Number}},
text: {body: "Welcome back my friend"},
}
let headers = {"Content-Type": "application/json", "Authorization":"Bearer {{token}}"
}
let params = {}
try
{
const resp = await axios.post(url, {payload}, {headers, params});
log("POST RESP",resp)
}
catch(error)
{
throw error;
}
Try below code.
let url = 'https://graph.facebook.com/<Version>/<Your Phone number ID>/messages';
let payload = {
'messaging_product': 'whatsapp',
'recipient_type': 'individual',
'to': '123456789012',//Recipient Phone Number
'type': 'text',
'text': {
'body': 'Welcome back my friend'
}
};
let headers = {
'Authorization': 'Bearer <Your Temporary access token>',
'Content-Type': 'application/json'
};
axios.post(url, payload, {
headers: headers
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

How to code Multipart-form POST REQUEST using apollo-datasource-rest

I want to code the multipart-form POST REQUEST below using apollo-datasource-rest
My attempt to code this leads to a BAD REQUEST error
const { RESTDataSource } = require('apollo-datasource-rest');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
class SalesforceApi extends RESTDataSource {
constructor() {
super();
this.initialize({});
this.getAccessToken()
.then((accessToken) => {
this.headers = {
Authorization: `Bearer ${accessToken}`,
};
});
}
async getAccessToken() {
console.log('Getting Salesforce access token');
try {
const response = await this.post(
'https://test.salesforce.com/services/oauth2/token',
{
username: 'FILTERED#FILTERED',
password: `${'FILTERED'}`,
grant_type: 'password',
client_id: 'FILTERED',
client_secret: 'FILTERED',
},
{
headers: {
'Content-Type': 'multipart/form-data',
},
},
);
const { accessToken } = response;
console.log(`ChangeGear sessionId: ${accessToken}`);
return accessToken;
} catch (error) {
console.log(`${error}`);
}
return 'No access token!!!';
}
module.exports = SalesforceApi;
[server:salesforce:local] POST https://test.salesforce.com/services/oauth2/token (343ms)
[server:salesforce:local] Error: 400: Bad Request
If memory serves correctly, form data is serialized slightly differently hence why the FormData interface exists. And the apollo-datasource-rest's this.post method is just a wrapper around fetch, so something like the below should work.
Instead of passing the body as a JSON object, try something like this
const formData = new FormData();
formData.append('username', 'FILTERED#FILTERED');
// ... more append lines for your data
const response = await this.post(
'https://test.salesforce.com/services/oauth2/token',
formData
{
headers: {
'Content-Type': 'multipart/form-data',
},
},
);

Can't able to call simple API

I just want to call simple API but can't able to call. If I tried to call in Postman then get proper response.
Look at my code
Future<AppServiceModel> getAllItems({String pageID = ""}) async {
final String _url = "http://www.textsite.com/api/app-view?page_id=";
final finalURL = Uri.encodeFull(_url);
try {
return http.get(finalURL, headers: {
HttpHeaders.contentTypeHeader: 'application/x-www-form-urlencoded',
HttpHeaders.acceptHeader: "application/json",
HttpHeaders.authorizationHeader: 'Bearer $accessToken'
}).then((response) {
Map<String, dynamic> _resDic =
Map<String, dynamic>.from(json.decode(response.body));
print('===>> Response : $_resDic');
return AppServiceModel.fromJson(_resDic);
});
} catch (e) {
print("Error: $e");
return null;
}
}
I also tried to pass QueryParameters by following How do you add query parameters to a Dart http request?
But each time get response
Response : {code: 7, msg: Your login session has expired. Please login again to continue., data: []}
I'm damm sure, passing right TOKEN.
Below is output of Postman

node.js / axios AUTHENTICATION_FAILURE with PayPal Subscriptions API

I'm using Axios to activate a PayPal subscription since the NODE SDK doesn't support the subscription activation. For doing so I've created this method that generate a PayPal access token:
let getAccessToken = async () => {
return await axios(options).then((response) => {
return response.data.access_token
});
}
the options contains the following details:
const options = {
method: 'post',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Credentials': true
},
data: qs.stringify(data),
auth: {
username: PAYPAL_CLIENT_ID,
password: PAYPAL_CLIENT_SECRET
},
url: 'https://api.sandbox.paypal.com/v1/oauth2/token'
}
this working fine but I'm having some problems activating the subscription, this is the method that handle this:
let activateSubscription = async (accessToken, subscriptionId) => {
return await axios.post(
`${baseURL}/v1/billing/subscriptions/${subscriptionId}/activate`,
{
headers: {
"Authorization": `Bearer ${accessToken}`,
"Content-Type": 'application/json'
}
}).then((data) => {
return true;
})
.catch((error) => {
console.log(error.response.data);
return false;
});
}
Essentially I pass the generated accessToken and the subscriptionId, but I get as response this:
{
name: 'AUTHENTICATION_FAILURE',
message: 'Authentication failed due to invalid authentication credentials or a missing Authorization header.',
links: [
{
href: 'https://developer.paypal.com/docs/api/overview/#error',
rel: 'information_link'
}
]
}
My suspicion was that the generated token was incorrect, so I tried it in postman sending this request:
{{host}}/v1/billing/subscriptions/I-7D10FGKVNMD0/activate
and the returned content is 204 which is okay according to what doc says here.
The request seems correct, what am I doing wrong?
You're setting the headers wrong. From the pastebin:
data: '{"headers":{"Authorization":"Bearer A21AAEj_0lJjny7Hc1aL7l5irIxOqOjyW_pSfT2WC9APAQFXHTYzKL0womW1mZvS6mKWsWMytMc6H6NIMPMnOK7zhzHKHsSAw","Content-Type":"application/json"}}',
headers: {
Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json;charset=utf-8',
'User-Agent': 'axios/0.19.2',
'Content-Length': 170
},
So, PayPal isn't actually getting your Authorization header

No response message after calling an API

Future<EventObject> addStudentToSubject(String studentCode, String subjectid) async {
try {
final encoding = APIConstants.OCTET_STREAM_ENCODING;
final response = await http.post('${APIConstants.API_BASE_LIVE_URL}/controller_educator/add_student_to_subject.php',
headers: {
'Accept': 'application/json',
},
body: {
'stud_code': studentCode,
'subj_id': subjectid
},
encoding: Encoding.getByName(encoding)
);
print("YAWA" + response.body);
} catch (Exception) {
return EventObject();
}
}
Is there something wrong with my code why i theres no response message??
Logcat just says "I/flutter ( 5013): YAWA"
Don't know what i'm missing.
I do not believe your API does not work in Postman. Can you indicate what status code did you get in Postman?
The problem in your code is your not checking the status code response of your API. The POST request you have called has probably had an empty body. Some POST request only returns the status code.
You should always check the status code of the API. If it returns 200 means your API has processed your request successfully.
final encoding = APIConstants.OCTET_STREAM_ENCODING;
final response = await http.post('${APIConstants.API_BASE_LIVE_URL}/controller_educator/add_student_to_subject.php',
headers: {
'Accept': 'application/json',
},
body: {
'stud_code': studentCode,
'subj_id': subjectid
},
encoding: Encoding.getByName(encoding)
);
print(${response.statusCode});
if (response.statusCode == 200) {
String data = response.body;
print(data);
} else {
print(response.statusCode);
}