Posts tagged with api

An unofficial Forge API

You might not know this but Forge already has an API, it's just not a documented and feature complete one. Open up your dev tools and inspect the web requests being sent while you do various stuff on Forge.

Marcel Pociot published a new package called Blacksmith (great name Marcel) that can make calls to that API. Here are a few code examples taken from the readme:

$activeServers = $blacksmith->getActiveServers();

$server = $blacksmith->getServer(1);

$sites = $server->getSites();

$newSite = $server->addSite($site_name, $project_type = 'php', $directory = '/public', $wildcards = false);

$jobs = $server->getScheduledJobs();

$newJob = $server->addScheduledJob($command, $user = 'forge', $frequency = 'minutely');

Very cool stuff. Because the Forge API doesn't include a method to login, the package will under the hood just submit a filled in login form.

An official API for Forge has been on my wishlist for quite some time. Because Forge's code base already includes an API my guess is that it wouldn't be too work to grow it in to a full, publicly available one. Though I surely cannot read Taylors mind, I think that if there were some more indications that a Forge API would be used by enough people, there's a higher chance that an official API would be built. I think the only reason why the API hasn't been built yet is because not enough people are asking for it. It makes sense for Taylor to only work on things that would actually be used. So if you are using Forge and do want an official API go ahead and star the BlackSmith package on GitHub and make some noise about it.

Read more

Laravel-fractal v2 has been released

by Freek Van der Herten – 1 minute read

Last week v2 of laravel-fractal was released. This package is a developer friendly wrapper around the League's Fractal package. It a Laravel context it can be used to transform your Eloquent models to JSON output for an API. Think of it as toJson (or toArray) on steroids. This is how you can work…

Read more

Join thousands of developers

Every two weeks, I share practical tips, tutorials, and behind-the-scenes insights from maintaining 300+ open source packages.

No spam. Unsubscribe anytime. You can also follow me on X.

Preventing API drift with contract tests

In an older post on his blog Adam Wathan shared an interesting approach on how to prevent API drift between a test mock and an actual implementation.

One of the risks of writing your own test doubles is that the API of the double can fall out of sync with the API of the real implementation.

In this screencast I walk through an example that explains:

  • How interfaces can provide a false sense of security
  • Why tests make better contracts than interfaces
  • How to run multiple implementations against a shared set of contract tests

If you’ve ever had issues with API drift, try this approach and let me know how it works for you.

https://adamwathan.me/2016/02/01/preventing-api-drift-with-contract-tests/

Read more

Learn about grant types in Laravel Passport

Laravel Passport is an easy to use OAuth2 server that was released alongside Laravel 5.3. Mohamed Said wrote an excellent guest post at Laravel News about the grant types used in Passport.

OAuth2 is a security framework that controls access to protected areas of an application, and it’s mainly used to control how different clients consume an API ensuring they have the proper permissions to access the requested resources.

Laravel Passport is a full OAuth2 server implementation; it was built to make it easy to apply authentication over an API for laravel-based web applications.

https://laravel-news.com/2016/08/passport-grant-types/

Read more

How to use WordPress as a backend for a Laravel Application

Recently Eric L. Barnes put a new coat of paint on Laravel News. Behind the scenes there were some changes as well. In a new post he explains how he integrated the Wordpress backend with a Laravel app.

Last week I relaunched Laravel News, and the new site is running on Laravel with WordPress as the backend. I’ve been using WordPress for the past two years, and I’ve grown to enjoy the features that it provides. The publishing experience, the media manager, the mobile app, and Jetpack for tracking stats.

I wasn’t ready to give these features up, and I didn’t have the time to build my own system, so I decided to keep WordPress and just use an API plugin to pull all the content I needed out, then store it in my Laravel application. In this tutorial, I wanted to outline how I set it all up.

https://laravel-news.com/2016/08/wordpress-api-with-laravel/

Read more

The next version of Laravel News has been launched

Earlier today laravel-news.com, the official Laravel news source, received a new coat of paint. In a post announcing the launch Eric shares how the site works behind the curtains.

During this move, I have redone the way the site is powered. Previously it ran on WordPress with a custom theme I put together, it worked fine but added new features, and sections became harder and harder, and I wanted the ability to use what I am comfortable with, Laravel. However, I didn’t want to give up the media library and editing experience of WordPress.

So to have the best of both worlds I kept the old site on WordPress and used the WP Rest API paired with the Laravel Scheduler. This allows me to automatically sync data from WordPress into my database without having to rebuild an entire CMS admin area. I have the same setup for the podcast section, and it hooks into the Simplecast API to pull those over.

https://laravel-news.com/2016/08/welcome-to-the-next-version-of-laravel-news/

I sure would like to read a tutorial on how that sync works in detail.

Read more

Laravel Analytics v2 has been released

by Freek Van der Herten – 2 minute read

One of our more popular packages is laravel-analytics. The package makes it easy to fetch information such as pageviews, top referrers, etc... from the Google Analytics API. In our Blender-based projects we use the fetched data to display a nice chart in the admin section: Laravel-analytics is one…

Read more

Test Driven API Development using Laravel, Dingo and JWT with Documentation

In a new tutorial posted at dotdev.co Diaa Fares shows a good way to develop API's using Laravel. Along the way he touches on the Dingo packages, JSON Web tokens and documentation generation.

Let’s look at everything we will cover: Landmark 1: Prepare our TDD environment and creating our first test. Landmark 2: Installing and configuring Dingo API package. Landmark 3: What are Transformers, why the need for them and how to use thephpleague/fractal as our transformation layer. Landmark 4: Introduction about JWT and how to use tymondesigns/jwt-auth for our token based authentication. Landmark 5: How to use laravel-apidoc-generator to generate nice documentation for our API. So, pack your bags and let’s dive into our journey!

https://dotdev.co/test-driven-api-development-using-laravel-dingo-and-jwt-with-documentation-ae4014260148#.iynir3ftm

Read more

Getting package statistics from Packagist

by Freek Van der Herten – 2 minute read

At my work I'm currently creating a new dashboard. That's a fancy term for an html page sprinkled with some Vue magic that will be displayed on tv screen at the wall of our office. I won't say much about the dashboard itself on this post, but I'll make sure to write something on that in the near…

Read more

How to setup and use the Google Calendar API

by Freek Van der Herten – 4 minute read

For a project I'm working on I needed to interact with a Google Calendar. If you've ever worked with some API's by Google then you know their documentation can be very confusing. It's not that they don't have documentation, but code examples of common use cases are simply not present. You must wade…

Read more

Route model binding using middleware

Our team is currently working on a Spark app. Spark makes is real easy to add an API that can be consumed by the users of the app. The generation of API tokens and authentication middleware comes out of the box. It all works really great.

In our API the a team owner can fetch information on every member on the team and himself. The url to fetch info of a user looks something like this: /users/<id-of-user>. Nothing too special. But we also want to make fetching a user's own information as easy as possible. Sure, the user could look op his own userid and then call the aforementioned url, but using something like /users/me is much nicer. In this way the user doesn't have to look op his own id. Let's make that possible.

In our app we use these functions to get the the current user and team:

/**
 * @return \App\Models\User|null
 */
function currentUser()
{
    return request()->user();
}

/**
 * @return \App\Models\Team|null
 */
function currentTeam()
{
    if (!request()->user()) {
        return;
    }

    return request()->user()->currentTeam();
}

The route look something to get the user data looks something like this:

Route::post('/users/{userId}', 'UserController@show');

My first stab to get /users/me working was to leverage route model binding. In the RouteServiceProvider I put this code:

$router->bind('userId', function ($userId) {
   if ($userId === "me") {
      return currentUser();
   }

   $user = currentTeam()->users->where('id', $userId)->first();

   abort_unless($user, 404, "There's no user on your team with id `{$id}`");

   return $user;
});

Unfortunately this does not work. When Laravel is binding route parameters the authentication has not started up yet. At this point currentUser and currentTeam will always return null.

Middleware comes to the rescue. Route-middleware is processed at a moment when authentication has started up. To make /users/me work this middleware can be used:

namespace App\Http\Middleware;

use Closure;

class BindRouteParameters
{
    public function handle($request, Closure $next)
    {
        if ($request->route()->hasParameter('userId')) {
            $id = $request->route()->parameter('userId');

            $user = $this->getUser($id);

            abort_unless($user, 404, "There's no user on your team with id `{$id}`");

            $request->route()->setParameter('userId', $user);
        }

        return $next($request);
    }

    public function getUser(string $id)
    {
        if ($id === 'me') {
            return currentUser();
        }

        return currentTeam()->users->where('id', $id)->first();
    }
}

There are two things you must do to use this middleware. First: it's route middleware so you such register it as such at the http-kernel.

// app/Http/Kernel.php

...
/**
 * The application's route middleware.
 *
 * These middleware may be assigned to groups or used individually.
 *
 * @var array
 */
protected $routeMiddleware = [
...
'bindRouteParameters' => \App\Http\Middleware\BindRouteParameters::class,
]

Second: you must apply the middleware to certain routes. In a default Spark app you'll find all api-routes in a file at app/Http/api.php. That file starts with this line:

Route::group(['prefix' => 'api', 'middleware' => ['auth:api']], function () {
...

Just add the bindRouteParameters middleware to the group:

Route::group(['prefix' => 'api', 'middleware' => ['auth:api', 'bindRouteParameters']], function () {
...

I'm currently using the above solution in my app. You could make a solution that's more generic by checking if the parameters ends with orMe. Here's an example how that might work:

namespace App\Http\Middleware;

use Closure;

class BindCurrentUserRouteParameter
{
    public function handle($request, Closure $next)
    {
        collect($request->route()->parameters())
            ->each(function ($value, $parameterName) use ($request) {
                if (!ends_with($parameterName, 'orMe')) {
                    return;
                }

                if ($value === 'me') {
                    $request->route()->setParameter($parameterName, currentUser());
                }
            });

        return $next($request);
    }

If you have any questions about this approach or have any ideas how to make it better, let me know in the comments below.

Read more

Building a GIF search engine with React

Over at the Tighten blog Samantha Geitz posted an amazing introduction to React. She starts off by clearly explaining how to setup the environment (webpack and a few dependencies). After making sure that it all works, she continues by building a GIF search engine. Along the way the core concepts of React are explained. If you're in any way interesting in learning React, I warmly recommend reading the entire piece.

React itself is reasonably well-documented and easy to pick up, once you can shift your thinking to align with its conventions. The problem is, if you want to build robust apps, the V in MVC probably isn't going to cut it, and you have to dive into the often-confusing ecosystem surrounding React.

In this series, we're going to walk through the stages of building a React application — an app that lets you search the Giphy API and displays results, similar to what Giphy has on its own website.

In this first article, we are going to build the application using only React (with Webpack for asset compilation).

http://blog.tighten.co/react-101-building-a-gif-search-engine

I'm looking forward to read the next articles of this series.

Read more

API Token Authentication in Laravel 5.2

Typically my applications have a UI and authentication is done through a simple login page. Obviously for a RESTful API, having a login page isn't ideal. Instead, my hope was to have users append an api_token to the end of their query string and use that to authenticate their request. I was happy to find that 5.2 also ships with a TokenGuardlink class that allows you to do exactly that, but the documentation on getting it to work was a bit thin, so here you go.
https://gistlog.co/JacobBennett/090369fbab0b31130b51

Read more

Laravel and Content Negotiation

Chris Fidao posted a good tutorial on how to use some lesser known built-in Laravel methods to handle content negotiation.

An HTTP client, such as your browser, or perhaps jQuery's ajax method, can set an `Accept` header as part of an HTTP request.

It's up to the server to follow the rules of HTTP. When a request comes to our application, it's pretty easy to ignore these rules, as our frameworks generally let us return whatever we want.

Laravel provides a nice, easy way to check if a request "wants json".

http://fideloper.com/laravel-content-negotiation

Read more

Exporting json for a mobile app using Laravel

Every year the city of Antwerp (my hometown :-)) organises lots of activities, such as an Ice rink, a Christmas market, a Santa Run and of course fireworks in the month of december. To inform people of which activities are happening where and when my team and I created a mobile app commissioned by the city council. The app is called "Winter in A" and is available on both Android's Play Store and iOS' App Store.

The administrators of the app can enter content in a custom installation of Blender, our Laravel based application. Blender will write of a bunch of json-files that are read by the mobile apps. Here's the file for all the events (english localization): https://api.winterapp.be/en/events.json. We use our homegrown laravel-fractal package to easily transform database records to json. Here's the export handler that's in charge of the exporting of events:

namespace App\Services\Export\ExportHandlers;

use App\Repositories\EventRepository;
use App\Services\Export\ExportHandler;
use App\Services\Export\Transformers\EventTransformer;

class Events implements ExportHandler
{
    /**
     * @var \App\Repositories\EventRepository
     */
    protected $eventRepository;

    public function __construct(EventRepository $eventRepository)
    {
        $this->eventRepository = $eventRepository;
    }

    /**
     * Get the json for the given locale.
     *
     * @param string $locale
     *
     * @return mixed
     */
    public function getJsonForLocale($locale)
    {
        return fractal()
            ->collection($this->eventRepository->getAllOnline())
            ->transformWith(new EventTransformer($locale))
            ->toJson();
    }
}

The EventTransformer itself:

namespace App\Services\Export\Transformers;

use App\Models\Event;
use App\Services\Export\Format;
use App\Services\ValueObjects\Period;
use League\Fractal\TransformerAbstract;
use Spatie\MediaLibrary\Media;

class EventTransformer extends TransformerAbstract
{
    /**
     * @var
     */
    protected $locale;

    public function __construct($locale)
    {
        $this->locale = $locale;
    }

    public function transform(Event $event)
    {
        return [
            'id' => $event->id,
            'name' => $event->translate($this->locale)->name,
            'text' => htmlToMarkdown($event->translate($this->locale)->text),
            ...
            'images' => $event->getMedia('images')->map(function (Media $media) {
                return [
                   'thumb' => $media->getUrl('thumb'),
                   'full' => $media->getUrl('full')
                ];
            }),
        ];
    }
}

To handle peaks in usage of the app we use CloudFlare. In this article they explain what they do. Cloudflare has this awesome feature called "Always online", to make sure the API is online even if our server is not.

The first events of Winter in Antwerp are starting tomorrow. The last ones are scheduled in the first days of 2016. I'll share some more tidbits of the code then.

Read more

A Fractal service provider for Laravel

by Freek Van der Herten – 1 minute read

Today I released a new package called laravel-fractal. It provides a Fractal service provider for Laravel. If you don't know what Fractal does, take a peek at their intro. Shortly said, Fractal is very useful to transform data before using it in an API. Using Fractal data can be transformed like…

Read more

GraphQL: A data query language

When we built Facebook's mobile applications, we needed a data-fetching API powerful enough to describe all of Facebook, yet simple enough to be easy to learn and use by our product developers. We developed GraphQL three years ago to fill this need. Today it powers hundreds of billions of API calls a day. This year we've begun the process of open-sourcing GraphQL by drafting a specification, releasing a reference implementation, and forming a community around it at graphql.org.
https://code.facebook.com/posts/1691455094417024/graphql-a-data-query-language/

There's already a package to use GraphQL with Laravel.

Read more