You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
0 Hrs
22 Min
59 Seg
Curso de API REST con Laravel

Curso de API REST con Laravel

Profesor Italo Morales F

Profesor Italo Morales F

Versi贸n 2: recurso

12/18
Resources

How to configure a resource in version two?

Configuring resources in your application may seem challenging at first, especially when it comes to handling multiple versions. However, this process is essential to ensure that you deliver the right data to the right users. When moving from version one to version two, we need to properly configure the data to avoid conflicts and ensure proper data integrity.

For version two, the client requires different fields. This involves making some adjustments to the controller and the application's data structure. Here is how you can configure a resource in version two efficiently:

How to return a resource from the controller?

To accomplish this, we first make sure that our controller is properly configured. A simple example implementation of a resource configuration looks like this:

public function show($id) { return new PostResource(Post::findOrFail($id));}

This code is the starting point that allows us to return a specific resource from the Post model, updated for the version you want to implement.

How to specify the fields in an array?

One of the most important steps is to define the fields that will be returned in version two. You can specify these fields inside an array as follows:

public function toArray($request) { return [ 'id' => $this->id, 'post_name' => $this->title, 'content' => $this->content, 'author' => [ 'name' => $this->user->name, 'email' => $this->user->email, ], 'created_at' => $this->created_at->toDateTimeString(), ];}

Here we have decided to rename the title field to post_name, we omit the extract field and emphasize the content instead. We also include author as a sub-array, with its name and email, which gives us a clear example of how to work with relationships.

Why use relationships in our resources?

Relationships are fundamental to link related entities in our database. In this case, we want each post to be linked to a user. This is done by defining a belongsTo relationship:

public function user() { return $this->belongsTo(User::class);}

With this relationship configuration, you can easily access any related data, such as the name or email of the author of a post.

How to test the configuration in Postman?

Testing your configurations is crucial to identify bugs before releasing your application to production. You can use tools like Postman to simulate API requests. To verify if your configurations work correctly, you need to:

  1. Make a GET request to the corresponding endpoint, in this case to the post resource with id 1: /api/v1/posts/1 for version one, and /api/v2/posts/1 for version two.
  2. Notice the different fields that are returned depending on the API version you are requesting.

This not only demonstrates your application's ability to handle different versions, but also allows you to simulate how clients will receive data depending on the API version they are using.

By working with versioned resources, you not only protect your application from abrupt changes in the data structure, but also ensure that your users have a consistent and predictable experience. Take advantage of these configurations to master the management and versioning of your API with confidence and proactivity. Keep exploring and improving your software development skills!

Contributions 7

Questions 1

Sort by:

Want to see more contributions, questions and answers from the community?

Nuevamente vuelvo a recomendar el Curso de Postman 馃憖
.
Relamente alguien que desarrolla el frontend no te va a estar hablando para preguntarte cu谩les son los campos que vas a mandar, etc. Si no que t煤 como el desarrolador de API debes generar una documentaci贸n que te diga cu谩les son los endpoints y qu茅 retorna, por ejemplo, esta ser铆a la documentaci贸n de Conekta (una pasarela de pagos):
.
Documentaci贸n del API Conekta
.
Aqu铆 se alcanza a ver c贸mo del lado izquierdo se encuentra la descripci贸n y del lado derecho el c贸digo para hacer el request en diversos lenguajes, eso es lo que t煤 tienes que generar.
.
Ahora, por eso recomiendo el curso de Postman, porque Postman, a medida que vas haciendo tus tests y pruebas, va registrando cada respuesta que te devuelve tu API, y al final del d铆a 茅l va a guardar todo eso y con un simple click te va a generar una p谩gina de documentaci贸n muy similar a la de Conekta en varios lenguajes de programaci贸n 馃槃

Nuevamente YO jaja!
Un tip para que no tengan sus endpoints de v1 y v2 en el mismo archivo es que separen los mismo por un archivo y los registren en el app>>Providers>>RouteServiceProvider.php.

De la siguiente manera:

$this->routes(function () {
            Route::prefix('api/v1')
                ->middleware('api')
                ->namespace($this->namespace)
                ->group(base_path('routes/api/v1.php'));

            Route::prefix('api/v2')
                ->middleware('api')
                ->namespace($this->namespace)
                ->group(base_path('routes/api/v2.php'));

            Route::middleware('web')
                ->namespace($this->namespace)
                ->group(base_path('routes/web.php'));
        });

Les comparto el c贸digo del archivo
App/Http/Resources/V2/PostResource.php

  public function toArray($request)
  {
    return [
      'id' => $this->id,
      'post_name' => $this->title,
      'slug' => $this->slug,
      'content' => $this->content,
      'author' => [
        'name' => $this->user->name,
        'email' => $this->user->email,
      ],
      'created_at' => $this->published_at
    ];
  }

Alternativa a postman

Les recomiento tambien el uso de https://insomnia.rest/ ya que postman tiene demasiadas funciones por lo que aveces puede consumir 500 Mb, y ser algo agobiante.
Tambien se actualizaciones frecuentemente.

se debe documentar como hacer request y que response devuelve cada endPoint, pero tanto los tester como frontEnd deben poder hacer algo como consultar por medio de postman con el estandar rest(verbos) y pues con el response saben como codificar el front

alguien me puede decir cuando se hablo de configurar las funciones que estan en los modelos o si vienen de otro curso public funtion getExecerptAttribute() por ejemplo
Genial el curso