(This page has no text content)
(This page has no text content)
THOMAS GAMBORG NØRGAARD Build an API with Laravel
First published by Wacky Studio 2019 Copyright © 2019 by Thomas Gamborg Nørgaard All rights reserved. No part of this publication may be reproduced, stored or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning, or otherwise without written permission from the publisher. It is illegal to copy this book, post it to a website, or distribute it by any other means without permission. Thomas Gamborg Nørgaard asserts the moral right to be identified as the author of this work. Thomas Gamborg Nørgaard has no responsibility for the persistence or accuracy of URLs for external or third-party Internet Websites referred to in this publication and does not guarantee that any content on such Websites is, or will remain, accurate or appropriate. Designations used by companies to distinguish their products are often claimed as trademarks. All brand names and product names used in this book and on its cover are trade names, service marks, trademarks and registered trademarks of their respective owners. The publishers and the book are not associated with any product or vendor mentioned in this book. None of the companies referenced within the book have endorsed the book. First edition Proofreading by Sille Justesen Krogh Editing by Christian Nørrelund This book was professionally typeset on Reedsy. Find out more at reedsy.com
Contents Errata iv Code samples and conventions v Why Laravel? viii Prerequisites ix The Github Repository x Introduction 1 The JSON:API specification 13 Planning 74 Build your API 137 Test-drivenWorkflow 217 Books 335 Don’t repeat yourself 476 Finishing up 531 About the Author 746
Errata Since this is our first book, errors will most certainly have snuck in. You can help support the book by sending an email with any errors yourmight have found to hello@wackystudio.com along with the chapter and section title. As soon as we are informed about an error, we will fix it and release an update to the book. If you have feedback, we would love to hear from you as well. * * * iv
Code samples and conven ons In this book, we will reference a bunch of technical things, especially when it comes to API endpoints and code samples. The conventions used to show an API endpoint follows the protocol below: VERB: /api/endpoint?with=possible&query=params The VERB part references the HTTP verb, we will touch upon this later in the book, but for now these are: GET, POST, PUT, PATCH andDELETE. Next, you have the endpoint itself that indicates an intention. Lastly, you have the query parameters, which are often used for sorting and such. To give a more precise example, here is an example of a more common endpoint for querying books from a bookstore backend: GET:/books?include=author As youmight also have noticed by now, we use bold text to emphasize certain technical terms. In this book, we will also show examples of a response payload in JSON. Let’s take a look at how that will be shown: v
{ "data": [{ "type": "books", "id": 1, "attributes": { "title": "Build an API with Laravel", "body": "Lorem ipsum", "created": "2019-02-01 00:00:00", "updated": "2019-02-01 00:00:00" }, "relationships": { "author": { "data": { "id": 1, "type": "authors" } } } }], "included": [ { "type": "authors", "id": 1, "attributes": { "name": "Wacky Studio" } } ] } Let’s cover the code samples you will find in this book first. Since this book is centered around building an API using Laravel and Laravel is developed in PHP, most code will be PHP code. The code provided should not be considered applicable in production— it’s written with the intention of teaching in mind. We strive to write code following best practices, as much as possible. You might find areas where this is not the case, but keep in mind that we also strive to write code, where it is vi
as easy to get a technical points across as possible. This book has been written with syntax highlighting enabled. How this is interpreted is different depending on the platform, e-readers and chosen theme. The following code is an example to see how your e-reader highlights the syntax. If you see beautiful colors you are in luck, otherwise we hope you can still follow along. <?php class Object { private $variable; public function __construct($parameter) { $this->variable = $parameter; } public function doSomething() { return 'did something'; } } ?> * * * vii
Why Laravel? There are a lot of reasons why we chose to write this book around Laravel. The biggest reason is that we use the framework in almost all of our applications and solutions. At the time of writing, we have been using Laravel for almost six years and have written over a dozen applications, varying from small to rather large sizes. Since our primary income comes from developing applications, we want the development time to be as short and cheap as possible. We don’t want to reinvent the wheel every time we start on a new project, we don’t want something that is extremely hard to deploy to a server, and we also want to make something that is not a nightmare to maintain later on. Laravel helpsusdealwithprecisely thoseproblems,whichmakesdevelopment a joy. * * * viii
Prerequisites This book is written with Laravel developers in mind. You do not have to be a super advanced and skilled developer to follow along, but bear in mind that this is not a book about the Laravel framework itself, but instead about how to write an API using Laravel. Therefore, you will have to have a basic understanding of Laravel to keep up. We certainly recommend that you have tried writing an application in the framework before reading, and that you know what we talk about when we mention: Client, Server, Request, Response, Routes, Controllers, Eloquent or Models, Migrations, Factories, Authentication, Authorization, and Validation. If most of these words are foreign to you, we recommend that you read up on Laravel before continuing. We will also be using Laravel Collections heavily, so an understanding of these – especially themap, filter, each, flatten, flatMap,merge, pluck, sort, unique and valuesmethods is necessary. Also, we expect that you know the basics around PHP, especially the basics around PSR-4 namespacing, how to import classes from other namespaces and so forth. In many IDE’s and editors, all this functionality can be installed with a simple plugin or will already built into the IDE or editor. * * * ix
The Github Repository Throughout this book, we will not only be building an API, but also touching upon various concepts where we will need code examples. All of these can be found in our Github repository at this address: https://github.com/WackyStudio/build-an-api-with-laravel For the code to the API we will be building, we have the entire application as well as every step of the process separated into small folders in our Github repository, which you can use if you need help or need to see how we have implemented a certain feature: Each step will add onto the next one and only contain the files that have been added or changed following the structure of our main Laravel application, so you can easily follow along: x
You don’t have to clone this repository from the beginning, but if you want to follow along in your code editor instead of the code examples in the book, you can do sowith the following commands in your terminal. Youwill have to be in the desired folder on your local system where the repository should be cloned down to, before running any of the commands. When you are ready, type the following command andmake sure you are in the right directory before cloning it: git clone git@github.com:WackyStudio/build-an-api-with-laravel.git If you are not using SSH you can clone through HTTPS like this: git clone https://github.com/WackyStudio/build-an-api-with-laravel. git xi
If you are not familiar with git, you can also download a zip file with the contents by visiting the repository with the link given previously in this section. * * * xii
1 Introduc on Welcome to Build an API with Laravel, where we, as the title reveals, will take a look at how to build an API using Laravel. First, we will be looking at an API from amore theoretical point of view. Don’t worry, we won’t bore you to death with small details, but rather give you a fundamental understanding, which we can build on from there. We will be looking at why we are using PHP and Laravel, and what makes it a great candidate for writing APIs. We will go through the JSON:API Specification and learn about the protocols and conventions, and how these can help us build a more consistent API that is easier for us to consume. We will look at how to plan an API, what to be aware of and what decisions you’ll have to make, depending on whether your API is public or private. Next, we will be looking at authentication, where we take a closer look at Laravel Passport and OAuth 2, which Laravel Passport is built upon. Here, we will go over the different grant types and what they are used for, to give you a clearer image of what you should choose for your applications. 1
BUILD AN API WITH LARAVEL Then, we’ll get to the heart of the matter, where we will be writing the actual API. We will start out with a rather simple case to give you a better picture of how to apply the knowledge you’ll get from this book and to have a common ground to build on. We will be looking at Test-driven Development, especially the parts that are relevant to API development, and through this use the great testing tools from Laravel to test our API and also get an excellentworkflowon top of it. Wewon’t go into every detail about Test-driven Development, since it’s a huge topic in itself and that’s notwhat this book is about. Wewill, however, use Test-driven Development to show you howwe can drive out our implementations, how we can refactor code to not having to repeat the same code over and over again, and get code that is easier to reuse. Lastly, wewill be looking at authorization and how you can authorize different parts of your API. We will end the book with a bonus chapter, where we will go over the client side of things and show you how you can consume your API using client implementations, which is a huge advantage to using a set of strict protocols which the JSON:API specification will give us. We hope you will enjoy reading this book as much as we have enjoyed writing it. We find that knowing how to build APIs has helped us a lot during our projects, since you can separate the concerns between frontend and backend, and thereby adapt to changes or new platforms, whichmight consume your API much easier. Let’s get to it! What is an API? To best describe what an API is, let’s imagine that our application or service is like a restaurant. The frontend of the application is where you sit at the table and eat, and the backend is the kitchen, where they prepare food for you. 2
INTRODUCTION Here, an API plays the role of themenu, where you can pick what you want the kitchen to cook for you. In programming terms, an API makes it possible for a frontend developer to request a specific task or resource from the backend. If you lookat amenu, youmightnotice that it consists of afinitepredetermined set of dishes: a collection of dishes that the kitchen knows how to cook and prepare for you. The same goes for an API, but instead of having dishes to choose from, you instead select between endpoints. Through endpoints, we can order our backend to prepare and send back some data for us. It could be a list of books for a bookstore or the latest comments for a blog post, depending on the service or application that serves a solution to a problem. Like a menu being divided into starters, main course and desserts, an API is divided into resources. We’ll be touching upon resources later— right now you just have to know that they exist. Much like a menu can have various designs, the same goes for APIs and the architecture behind. At the time of writing this book, there are many types of API architectures. Some architectures like SOAP are not used that muchmore, while others like GraphQL are new and exciting. Then there is the common technology like REST, which we are going to cover in this book. What is REST? REST stands forRepresentational State Transfer and is an architectural style used for communication between a server and a client. REST uses the HTTP orHypertext Transfer Protocol, as a base for the communication. We already use HTTP for transferring HTML and other media from servers to our clients. This is, for instance, what happens when you visit a website, so by building on an already familiar technology, REST is easily adaptable. REST sends data using either XML or JSON. Both of these languages are meant for transferring data, but also meant to be readable by humans, which also 3
BUILD AN API WITH LARAVEL makes error tracking in REST a lot easier. REST is platform and language independent, as long as you adapt to HTTP, you adapt to REST. Already established features of HTTP, like SSL encryption, make it possible to transfer encrypted data across from server to client, so there are a lot of advantages we get for free. A disadvantage is that REST is not stateful, meaning that the state is not carried along from one request to the other. Therefore, you always have to send some kind of context to the server for it to know what to deliver to you. This limitation stems fromHTTP itself, so this is most likely something you are already familiar with. Like HTTP, REST works through requests, where you “pull” data from the server. There is nowayof“pushing”data throughREST, although it is possible for the server to do server pushing, using the HTTP 2 standard, but even that is only initiated by a request. Since REST relies somuch onHTTP, there are some things we have to examine to understand REST and the way communication takes place. For instance, HTTPmethods, also called verbs, play a significant role in the intention for a REST request, as much as the HTTP Status code plays a significant role in the answers. These are the HTTP building blocks that make upmost of the base of REST communication. Let’s take a closer look at HTTP Verbs. HTTP verbs As mentioned earlier, HTTP verbs play a significant role in the intention of a request. The HTTP verb tells the server about how we, on the client side, intend to handle our data. How to handle data is often looked at from a CRUD perspective, which stands for: Create, Read, Update, Delete. As an example, imagine an application for a bookstore. The CRUDpart herewill be responsible for: Adding, Listing, Updating or Removing books from the bookstore. 4
INTRODUCTION GET A request with a GET verb is for reading data. That’s the only thing this verb tells our server. The API endpoint will determine whether we are reading a collection of resources or just a single resource. We will go much further into detail about collections and resources later in this book, but for now, to put it into context, let’s revisit the bookstore. Here, the resource is a book and a collection could be a stack of books. POST A request with a POST verb is for creating a resource. In other words, we use POST whenever we want to transfer new data from the client to the server. PUT and PATCH Both the PUT and the PATCH request is for updating or modifying data, but the way they are intended is a bit different. PUT verbs are used when all data for a resource is completely replaced with the data given by the client. PATCH verbs are used for a partial update ormodification, instead of replacing everything in the resource. Whether to usePUT orPATCH is all up to you and the needs of your application. The differencesmight be subtle, but they are there tomake it clear to the client making the request, what is actually happening. 5
BUILD AN API WITH LARAVEL DELETE A request with a DELETE verb is, much as the name implies, for deleting a resource. Now that we know a bitmore about howwe tell the server about our intentions using HTTP verbs, let’s look at how the server tells us about the response through status codes. Status Codes Status codes are used by the server to tell the client whether a request has been successfully completed. The areas that status codes cover are divided into 5 groups. Let’s take a look at a few from each group that we will be using the most: 2XX as Success The 2XX range are statuses that tell the client a request was successful. You would think that only one status was needed here, but in some cases where, for example, you create something, it would be nice to know if the resource has been created. Let’s take a look at a few of the statuses we’ll be using later. 200 OK The 200 status code, which tells the client that the entire request was successful, is the most common. You might think that it’s sufficient to use this one status and then addmore details about the request in the response payload, but remember that these statuses were created for HTTP and to solve a problem. Since REST is built upon HTTP, and HTTP uses its status codes to communicate how a request has been fulfilled, why reinvent the wheel? Better 6
Comments 0
Loading comments...
Reply to Comment
Edit Comment