#API Development (Based on Laravel up and Running )
REST Representational State Transfer
What is a REST-ful API
- Structured around resources
- Primarily use HTTP verbs
- Stateless
- Consistent
- Return JSON
In Laravel
- Use resource controllers
- index - lists all
- show - show single
- store - save one
- edit - show the edit view
- update - updates
- destroy - removes
Returning JSON
If you return a collection from a route, it will be JSON
- return Cat::all()
Headers
- Send non content information using 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
-
Embed resources in the primary resource
-
Embed just the foreign keys
-
?
-
Subresourse
-
Optional embedding
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
- Install with composer (297)
- Migrate
- Client apps pass a token (as a Bearer token)
Guzzle - send HTTP request
Basically sending a GET (or other verb) from PHP.
Passport’s API
/oauth prefix
- Authorize users with with OAuth
- Allow users to manage their clients and tokens
Passport’s Available Grant Types
Authenticate users in four ways
- Password grant - less common - username,password - mobile app
- Authorisation - most common - most complex - like Twitter/Facebook - token to communicatee
- Personal - tokens for testing API or when using API
- Synchroniser - tokens from the Laravel session
Is Synchroniser the one for me?
- Already authenticated users
- AJAX
- JSON Web Token with CSRF
Scopes
JSON API Spec
A document must contain at least one of :
- data
- errors
- meta
What NExt
Laracasts[https://laracasts.com/series/incremental-api-development]
Notes From Laracasts
- use Postman
- all is bad
- hide db structure
- no headers - response codes
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
- respond not found function (take a look at the Github repo for the API lessons)
- respondWithError 500 and set the status code
- respondNotFound 400
Authentication
Basic Auth
- Must be uisng ssl
- auth.basic - comes with laravel
Validation return 400 or 422
Created 201 Response.HTTP_NOt.FOUND