ArtisanTinkerer.github.io

Blog

View on GitHub

#API Development (Based on Laravel up and Running )

REST Representational State Transfer

What is a REST-ful API

In Laravel

Returning JSON

If you return a collection from a route, it will be JSON

Headers

Sending response headers in Laravel

return response (Cat::all())->header('X-thinkymeebob',9);

Reading request headerss in Laravek

$request->header('thinkymeebob');

Pagination

Just use paginate() instead of all()

return Cat::paginate(20);
return DB::table('cats')->paginate(20);

How to Get

GET /cats?page=x

Also returns next page information

Sorting and Filtering

No sorting in Laravel (Isn’t that what a DB is for? )

Just do an order by.

Filtering

pg 293 Laravel Up and Running

Transforming Results

** Use Fractal **

Nesting and Relationships

Read *Build APIs You Won’t Hate

API Authentication with Laravel Passport

Passport (Laravel 5.3 Only) makes it easy to set up an OAuth 2.0 server

OAuth - book Matt Frost

Guzzle - send HTTP request

Basically sending a GET (or other verb) from PHP.

Passport’s API

/oauth prefix

  1. Authorize users with with OAuth
  2. Allow users to manage their clients and tokens

Passport’s Available Grant Types

Authenticate users in four ways

  1. Password grant - less common - username,password - mobile app
  2. Authorisation - most common - most complex - like Twitter/Facebook - token to communicatee
  3. Personal - tokens for testing API or when using API
  4. Synchroniser - tokens from the Laravel session

Is Synchroniser the one for me?

Scopes

JSON API Spec

A document must contain at least one of :

What NExt

Laracasts[https://laracasts.com/series/incremental-api-development]

Notes From Laracasts

Response

return Response::json ‘data’ ‘errors’ - message and my error code

http codes as well 200 - OK 404 - return errrors 500

Create an APIController and extend it

Authentication

Basic Auth

Validation return 400 or 422

Created 201 Response.HTTP_NOt.FOUND