Insert data from DB to URL manager - yii

I want URL manager to process URL with the company name with my CompanyController. To do so dynamically I should get company names from my database.
Now I have such rule (but it's not dynamic):
'<alias:(vector|karnasch|tecnomagnete|ruko|bds-maschinen|exact)>' => 'company/view',
(vector|karnasch|tecnomagnete|ruko|bds-maschinen|exact) --> data to this line I want to get from database.
I can get this data (manually establish connection to db), but maybe it's another more beautiful solution with help of Yii functional. Thanks!

You can always create your custom UrlRuleclass. If you only want to parse incoming URLs you can simply return false from the createUrl() method. In the parseUrl() method you query the DB for your company names and inspect if the current URL matches. If not, you simply return false again.

Well, you don't need to do this, you just have to define the right pattern, e.g. :
'contact' => 'contact/form',
// other rules should be set before this one
'<alias:[-\w]+>' => 'company/view',
http://www.yiiframework.com/doc/guide/1.1/en/topics.url#using-named-parameters

Related

api platform - Create post requests with nested resources

I'm new to symfony and the api platform and I want to develop an api with specific routes.
I'm looking to do is create a post query with nested resources to add relationships between tables.
example: I have 3 tables (users, periods, articles). I need to create a post request to add a new post with the following structure:
URL: api/:userid/:period/item
:userID = user ID
:period = Period name
name = element name
This request must create a new article in my "articles" table by adding the identifier, the name of the period and the name of the article entered as a parameter.
So my question is how do I pass multiple parameters in my path and save them in the database using the api platform?
Thanks in advance !
You can use custom routes with API platform, which allow you to create a route that correspond to a custom query => but you need to have these data before setting them in your Api platform path.
First of all, I would use the query builder to create the query you need get the data you need, then you can use your method directly in your entity (more here https://api-platform.com/docs/core/controllers/).
You can set the route you want inside of the path of the route and set the different arguments you need like this:
'path' => '/books/{id}/publication'
here id is your argument coming from your repository function.

SharePoint change column id for REST requests

I recently started experimenting with the REST API for SharePoint 2013 Foundation and I am trying to return all entries in a list. My GET request returns the data I am looking for, but the IDs used to identify the columns in the list are not helpful for identifying what the information is (see images below). The column IDs between 'Title' and 'ID', in the second image, are a jumble of characters.
SharePoint List View
Response Data
Is there any way to configure the list to use the column names as IDs? Also, is there some significance to the characters currently used as IDs?
You will need to make a second request to get a listing of columns that includes the InternalName and the Title which is what you are trying to reference:
You can use this REST call:
_api/web/lists/GetByTitle('Project Details')/fields
or you can use CSOM:
using (ClientContext context = new ClientContext(url))
{
List list = context.Web.Lists.GetByTitle("Project Details");
context.Load(list, l => l.Fields);
context.ExecuteQuery();
foreach(Field field in list.Fields)
{
Console.WriteLine(field.Title);
Console.WriteLine(field.InternalName);
}
}
SharePoint automatically generates the InternalName and it is a read-only field, at least using REST. It'll be easier to get the Field Data to correlate the InternalName to the Title than changing the values.
The column you are referring to, between Title and Id, is the ID of the content type associated to the item. It is not a column ID.
The SharePoint REST API is OData compliant, so you can use the $select parameter to query for the neccesary fields.
http://server/site/_api/web/lists('guid')/items?$select=Column1,Column2
Please be aware though, lookup fields need to be expanded as well, otherwise you get only the Id of the lookup item.
http://server/site/_api/web/lists('guid')/items?$select=LookupColumn&$expand=LookupColumn/Title

Pull mass name list from database or in script?

I need to fill an input box with a first name and last name. The user will press "Randomize" and it will pull a random first and last name and fill the inputs.
My question is I'm not sure if I should put the names in tables (firstNames, lastNames) or just store them in a javascript file and pull straight from that.
I'm trying to follow the Single Responsibility Principle so I'm inclined to choose the former, but then I have two more models, two more seeders, two more tables, and probably a class to pull all that together. And then do I fill from a CSV file or just from a manually populated seeder? It seems like a lot of work and extra files for a 1-time use.
I know I'll get crap for this being an opinion based question but there is no one or where else to ask.
Also if you know of a place to ask these kind of questions that won't get me ripped apart I'd appreciate that.
I would suggest using the Faker PHP library. That way you wouldn't have to create extra tables, models, or have to worry about finding yourself fake data.
To install it in your project, simply add the dependency in your composer.json file. and run a composer update.
"require-dev": {
"fzaninotto/faker": "1.3.*#dev"
},
Then you can use it to create fake first and last names for you (in your controller most likely)
$faker = Faker\Factory::create();
$firstName = $faker->firstName;
$lastName = $faker->lastName;
Edit:
To add your own names you can either edit or override the name provider file located here.
I would like to suggest Fakerino a new fake generator PHP library, with a modern approach, easy to extend with custom data, custom fake data class, or pre-configured groups of data.
https://github.com/niklongstone/Fakerino
<?php
include ('../Fakerino/vendor/autoload.php');
use Fakerino\Fakerino;
$fakerino = Fakerino::create();
echo $fakerino->fake('Surname')->toJson(); //["Donovan"]
echo $fakerino->fake('NameFemale'); //Alice
//with configuration
$fakerino = Fakerino::create('./conf.php');
print_r($fakerino->fake('fake1')->toArray());
/*
Array(
[0] => Arthur
[1] => Doyle
)
*/
//conf.php
<?php
$conf['fake'] = array(
'fake1' => array('NameMale', 'Surname' => null),
'fake2' => array('NameFemale', 'Surname' => null)
);

Should we always validate resource id in url and body in HTTP PUT request?

Suppose I am updating a employee record
url - /api/employees/10
body -
{
id : 10,
name : xyz
}
Should I validate for the employee id in url is same as in response? Because one employee can hit the url himself but update the data of another employee by sending another value in the PUT body.
If you have to validate, it's likely that you want to use POST. A POST is not idempotent and you are supposed to manage the change.
PUT is idempotent, and it just creates a resource. It implies that you don't actually care what id 10 is and whether it is a new id or an existing id. You just replace id 10 with the resource you supply. You only use PUT when you know what the uri should be.
Yes, if the representation of the object in the body contains its own key, you should validate that it matches the key from the URL. It's an error for the client to try to PUT an object at /api/employees/10 that isn't a valid value for employee #10's record, so you should check for that and report it as an error just as you would check that the object has correct syntax.
I believe that the best error code to return in this case is 422 Unprocessable Entity, but I might be wrong about that.
Another thing you can do instead is don't include the key at all in the body. However I find that keeping the key in makes sense for consistency with the way the same type of object is represented in other parts of the API (possibly embedded inside other objects). This is especially true when using XML (although it looks like you are using JSON here).

RESTful API - How do I return different results for the same resource?

Question
How do I return different results for the same resource?
Details
I have been searching for some time now about the proper way to build a RESTful API. Tons of great information out there. Now I am actually trying to apply this to my website and have run into a few snags. I found a few suggestions that said to base the resources on your database as a starting point, considering your database should be structured decently. Here is my scenario:
My Site:
Here is a little information about my website and the purpose of the API
We are creating a site that allows people to play games. The API is supposed to allow other developers to build their own games and use our backend to collect user information and store it.
Scenario 1:
We have a players database that stores all player data. A developer needs to select this data based on either a user_id (person who owns the player data) or a game_id (the game that collected the data).
Resource
http://site.com/api/players
Issue:
If the developer calls my resource using GET they will receive a list of players. Since there are multiple developers using this system they must specify some ID by which to select all the players. This is where I find a problem. I want the developer to be able to specify two kinds of ID's. They can select all players by user_id or by game_id.
How do you handle this?
Do I need two separate resources?
Lets say you have a controller name 'Players', then you'll have 2 methods:
function user_get(){
//get id from request and do something
}
function game_get(){
//get id from request and do something
}
now the url will look like: http://site.com/api/players/user/333, http://site.com/api/players/game/333
player is the controller.
user/game are the action
If you use phil sturgeon's framework, you'll do that but the url will look like:
http://site.com/api/players/user/id/333, http://site.com/api/players/game/id/333
and then you get the id using : $this->get('id');
You can limit the results by specifying querystring parameters, i.e:
http://site.com/api/players?id=123
http://site.com/api/players?name=Paolo
use phil's REST Server library: https://github.com/philsturgeon/codeigniter-restserver
I use this library in a product environment using oauth, and api key generation. You would create a api controller, and define methods for each of the requests you want. In my case i created an entirely seperate codeigniter instance and just wrote my models as i needed them.
You can also use this REST library to insert data, its all in his documentation..
Here is a video Phil threw together on the basics back in 2011..
http://philsturgeon.co.uk/blog/2011/03/video-set-up-a-rest-api-with-codeigniter
It should go noted, that RESTful URLs mean using plural/singular wording e.g; player = singular, players = all or more than one, games|game etc..
this will allow you to do things like this in your controller
//users method_get is the http req type.. you could use post, or put as well.
public function players_get(){
//query db for players, pass back data
}
Your API Request URL would be something like:
http://api.example.com/players/format/[csv|json|xml|html|php]
this would return a json object of all the users based on your query in your model.
OR
public function player_get($id = false, $game = false){
//if $game_id isset, search by game_id
//query db for a specific player, pass back data
}
Your API Request URL would be something like:
http://api.example.com/player/game/1/format/[csv|json|xml|html|php]
OR
public function playerGames_get($id){
//query db for a specific players games based on $userid
}
Your API Request URL would be something like:
http://api.example.com/playerGames/1/format/[csv|json|xml|html|php]