Send new message MAILCHIMP, returns empty - mailchimp

I am sending an email individually with MAILCHIMP without using templates, but the return comes out empty, what would be the correct way to send the request message?
-The answer returns empty and the mail does not arrive
-This is my post method
route: http://localhost:6002/api/mailchimp/message/send
"message": [
{
"subject": "student",
"from_email": "ingenieria#uni.edu.pe",
"html":"<p>Estudia en la UNI</p>",
"text": "Estudia en la UNI",
"to": [
{
"email": "pedro.24#gmail.com",
"type": "to"
}
]
}
]
}
function
public function send(Request $request)
{
$message = $request->message;
$mailchimp = new MailchimpTransactional\ApiClient();
$mailchimp->setApiKey(env('MAILCHIMP_KEY'));
$response = $mailchimp->messages->send(
[
"message"=>$message
]
);
return response()->json($response, 200);
}
PD: in another method I receive the post using templates there if it works => $respuesta = $mailchimp->messages->sendTemplate(...)

I realized that in the json I send it has brackets [], and it shouldn't go, it would look like this and it worked
"message": {
"subject": "student",
"from_email": "ingenieria#uni.edu.pe",
"html":"<p>Estudia en la UNI</p>",
"text": "Estudia en la UNI",
"to": [
{
"email": "pedro.24#gmail.com",
"type": "to"
}
]
}
}

Related

Data from geoJSON API call in Larvel 5.8

I am trying to retrieve data from the weather.gov API - it returns the format in geoJSON and I am not sure how to actually get the data I want from it.
If I am using the weatherbit.io API, I have no issues as it returns JSON format in which I can pull from rather easily.
I am using GuzzleHTTP to make the API call.
I am playing around with learning APIs and I have an interest in weather so I figured I would work on an application in which I could pull information from the local weather station and output it in to readable format for users in a table.
The code I am currently using is:
$api_call = https://api.weather.xxx/points/LAT,LON;
$client = new \GuzzleHttp\Client();
$request = $client->get($api_call);
if ($request->getStatusCode() == 200) {
$weatherRequest = $request->getBody();
$requestedWeather = json_decode($weatherRequest);
$currentweather = $requestedWeather; ** THIS IS WHERE I NEED HELP ***
}
return $currentweather;
});
return view('currentweather', ["currentweather" => $currentweather]);
When I am returning $currentweather and var_dump it to the view, it gives me all the geoJSON data but I don't know how to correctly iterate through the data to pull the information I need.
When I pull from another API it gives a different JSON format which I can just pull like so:
$api_call = https://api.weatherbit.xx/v2.0/current?
$client = new \GuzzleHttp\Client();
$request = $client->get($api_call);
if ($request->getStatusCode() == 200) {
$weatherRequest = $request->getBody();
$requestedWeather = json_decode($weatherRequest);
$currentweather = $requestedWeather->data;
}
return $currentweather;
});
return view('currentweather', ["currentweather" => $currentweather]);
}
And when I use $currentweather in my view I can pull any data I need with the object string name. I am not sure how to pull the data when it's leading off with the #Context tag.
The data I want lies in the "properties" part of the geoJSON array and I just can't seem to figure out how to get that in the way I am currently using.
This is my geoJSON array return:
{ "#context": [ "https://raw.githubusercontent.xxx/geojson/geojson-ld/master/contexts/geojson-base.jsonld", { "wx": "https://api.weather.xxx/ontology#", "s": "https://schema.org/", "geo": "http://www.opengis.xxx/ont/geosparql#", "unit": "http://codes.wmo.xxx/common/unit/", "#vocab": "https://api.weather.xxx/ontology#", "geometry":
{ "#id": "s:GeoCoordinates", "#type": "geo:wktLiteral" }, "city": "s:addressLocality", "state": "s:addressRegion", "distance": { "#id": "s:Distance", "#type": "s:QuantitativeValue" }, "bearing": { "#type": "s:QuantitativeValue" }, "value": { "#id": "s:value" }, "unitCode":
{ "#id": "s:unitCode", "#type": "#id" }, "forecastOffice": { "#type": "#id" }, "forecastGridData": { "#type": "#id" }, "publicZone": { "#type": "#id" }, "county": { "#type": "#id" } } ], "id": "https://api.weather.xxx/points/xxx,xxx", "type": "Feature", "geometry": { "type": "Point", "coordinates": [ xxx, xxx ] }, "properties":
{ "#id": "https://api.weather.xxx/points/xxx,xxx", "#type": "wx:Point", "cwa": "xxx", "forecastOffice": "https://api.weather.xxx/offices/xxx", "gridX": 86, "gridY": 77, "forecast": "https://api.weather.xxx/gridpoints/xxx/xx,xx/forecast", "forecastHourly": "https://api.weather.xxx/gridpoints/xxx/xx,xx/forecast/hourly", "forecastGridData": "https://api.weather.xxx/gridpoints/xxx/xx,xx", "observationStations": "https://api.weather.xxx/gridpoints/xxx/xx,xx/stations", "relativeLocation":
{ "type": "Feature", "geometry": { "type": "Point", "coordinates": [ xxx, xxx ] }, "properties": { "city": "xxx", "state": "xx", "distance": { "value": xxxx.xxxxxxxxx, "unitCode": "unit:m" }, "bearing": { "value": 150, "unitCode": "unit:degrees_true" } } }, "forecastZone": "https://api.weather.xxx/zones/forecast/xxxxxx", "county": "https://api.weather.xxx/zones/county/xxxxxx", "fireWeatherZone": "https://api.weather.xxx/zones/fire/SCZ050", "timeZone": "America/New_York", "radarStation": "xxxx" } }
Thanks for your help!
Any member of the JSON object can be accessed via the same name on the object returned by json_decode. Your weatherbit example $requestedWeather->data works because everything is in a member called data. So... $requestedWeather->properties will get you what you want from the weather.gov API.
You can also pass true as a second argument to json_decode to get back a plain PHP array instead.
$requestedWeather = json_decode($weatherRequest, true);
var_dump($requestedWeather['properties']);
This is often recommended because JSON allows member names that are not valid PHP object property names (e.g., names containing hyphens).

relationship of an instantiated class - Laravel/Eloquent

I'm working on an api for a website, where I have the tables of blogs and categories
every blog belongs to category
and each category has many blogs
OK?
So, I created a BlogController and configured the routes to access the corresponding function.
/api/blog/ url via GET is redirected to the index function of my controller, and the function looks like this:
public function index()
{
$blog = Blog::with('category')->get();
return response()->json($blog, 200);
}
which returns this (correct)
[
{
"id": 1,
"title": "title from blog",
"body": "texto do meu blog",
"category_id": 1,
"created_at": "2018-09-05 21:08:21",
"updated_at": "2018-09-05 21:08:21",
"category": {
"id": 1,
"name": "Web development",
"created_at": "2018-09-05 20:54:54",
"updated_at": "2018-09-05 20:54:54"
}
}
]
/api/blog/ url via POST is redirected to the store function of my controller, to store the data in the database and the function looks like this:
public function store(Request $request)
{
$blog = new Blog($request->all());
$saved = $blog->save();
if ($saved) {
return response()->json($blog, 200);
}
return response()->json([
'message' => '400 Bad Request'
], 400);
}
then returns (missing category information)
{
"title": "title from blog",
"body": "texto do meu blog",
"category_id": "2",
"updated_at": "2018-09-06 00:56:13",
"created_at": "2018-09-06 00:56:13",
"id": 12
}
then, missing category information
after storing data in the database, I need it to come in response to category information for that specific blog
someone to help?
I can with
$blog->load('category');

remove data from laravel fractal

I'm using laravel-fractal to transform my data and here is a response
how can I delete data;
I made a search and I realized I need to use a Serializer;
But I just want to remove data for all includes(relations)
{
"data": [
{
"id": 1,
"name": "test name",
"status": null,
"tags": [
"first",
"second"
],
"created_at": "1396/9/3",
"contacts": {
"data": [
{
"value": "test#test.com",
"type": "email",
"icon": "fa fa-email"
}
]
}
},
{
"id": 2,
"name": "name test 2",
"status": null,
"tags": [],
"created_at": "1396/9/3",
"contact": {
"data": []
}
}
]
I found my answer at GitHub. The following answer is copied from thephpleague/fractal on GitHub:
You can write your own serializer for that.
class YourDataSerializer extends ArraySerializer
{
public function collection($resourceKey, array $data)
{
if ($resourceKey) {
return [$resourceKey => $data];
}
return $data;
}
public function item($resourceKey, array $data)
{
if ($resourceKey) {
return [$resourceKey => $data];
}
return $data;
}
}
Register your serializer with manager
$manager = new Manager();
$manager->setSerializer(new YourDataSerializer());
and when you want to have data or anything else you can pass in resourceKey to your Item or Collection as a third param.
$resource = new Collection($folders, new AccountFolderTransformer(), 'data');
use array serializer:
Fractal::create()
->item($item, new MyTransformer())
->serializeWith(new ArraySerializer())

Location response header returned from web-api to Swagger-ui

I am returning a Uri as the location header of the response from my web-api controller, as shown below:
[HttpPost]
public HttpResponseMessage PostTenant([FromBody] JObject value)
{
string tenantName;
try
{
tenantName = value.GetValue("name").ToString();
}
catch (Exception e)
{
throw new HttpResponseException(
this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, e));
}
try
{
DbInteract.InsertTenant(tenantName.Replace(" ", string.Empty));
var uri = Url.Link("TenantHttpRoute2", new { tenantName });
var response = new HttpResponseMessage(HttpStatusCode.Created);
response.Headers.Location = new Uri(uri);
return response;
}
catch...
}
The swagger-ui client makes the POST request, but the response headers don't contain the Location uri. It appears like this:
POST request from Swagger-ui
As you can see in the image, the RESPONSE HEADERS are
{
"content-type": null
}
The swagger JSON for this post request is:
"post": {
"tags": [
"Tenant"
],
"summary": "Add a new tenant",
"description": "Adds a tenant and returns admin user account information to be used in further calls.",
"consumes": [
"application/json",
"application/xml"
],
"produces": [
"application/json"
],
"parameters": [
{
"in": "body",
"name": "Tenant",
"description": "Name of the tenant must be alphanumeric without any special characters.",
"required": true,
"schema": {
"$ref": "#/definitions/CreateTenant"
}
}
],
"responses": {
"201": {
"description": "Tenant Inserted",
"headers": [
{
"description": "Location",
"type": "string"
}
]
},
"400": {
"description": "Invalid JSON Format of input"
},
"405": {
"description": "Tenant by this name already exists; Use PUT instead"
},
"500": {
"description": "InternalServerError"
}
}
}
What's wrong here? Why can't I see the response header in swagger-ui? Please let me know if you need more information. Thanks
The intent seems clear enough: a successful response returns a 201 Created with a Location header pointing at the newly created resource. Should work ...
I might remove the "produces" attribute, since you haven't defined any response anywhere.
Try with:
"headers" : { "Location" : { "description": "...", "type" : "string" } }
Instead of:
"headers" : []
so object instead of arrays.

Transform Laravel Eloquent result

When I execute this in my Controller
$data = User::with('teams')->find(2);
return response(['data' => $data]);
I get this as result
{
"id": 2,
"country_id": 1,
"first_name": "John",
"last_name": "Doe",
"created_at": "-0001-11-30 00:00:00",
"updated_at": "2015-02-02 23:08:21",
"full_name": "John Doe",
"teams": [
{
"id": 1,
"name": "Helpdesk medewerker",
"description": ""
},
{
"id": 2,
"name": "Retentie",
"description": ""
}
]
}
Im not interested in the full teams data, but only interested in the teamNames of the user.
I've done this by adding this
$data->each(function($user) {
$user->team_names = $user->teams->lists('name');
unset($user->teams);
});
I was wondering if this is the correct way of modifying the Eloquent result.
You can use an attribute accessor for that. Add this to your model:
protected $hidden = ['teams']; // hide teams relation in JSON output
protected $appends = ['team_names']; // add custom attribute to JSON output
public function getTeamNamesAttribute(){
return $this->teams->lists('name');
}
To change hidden and appends dynamically you can use the setter methods:
$data = User::with('teams')->find(2);
$data->setHidden(['teams']);
Filter out the columns you want in your first build.
$data = User::with(['teams' => function($query){
return $query->select('name');
}])->find(2);
Will output:
{
...
"teams": [
{
"name": "Helpdesk medewerker"
},
{
"name": "Retentie"
}
]
}
You can also use the lists method.
$data = User::with(['teams' => function($query){
return $query->lists('name');
}])->find(2);
Will output:
{
...
"teams": ["Helpdesk medewerker", "Retentie"]
}

Resources