Giter Site home page Giter Site logo

contributte / apitte Goto Github PK

View Code? Open in Web Editor NEW
61.0 9.0 37.0 1.53 MB

:wrench: An opinionated and enjoyable API framework based on Nette Framework. Supporting content negotiation, debugging, middlewares, attributes, annotations and loving openapi/swagger.

Home Page: https://contributte.org/packages/contributte/apitte/

License: MIT License

PHP 99.20% Makefile 0.22% HTML 0.58%
apitte api core http request response nette-framework nette

apitte's Introduction

Website πŸš€ contributte.org | Contact πŸ‘¨πŸ»β€πŸ’» f3l1x.io | Twitter 🐦 @contributte

Usage

To install the latest version of contributte/apitte use Composer.

composer require contributte/apitte

Documentation

For details on how to use this package, check out our documentation.

Version

State Version Branch Nette PHP
dev ^0.13 master 4.0+ >=8.1
stable ^0.12 master 4.0+ >=8.1

Development

See how to contribute to this package.

This package is currently maintaining by these authors.


Consider to support contributte development team. Also thank you for using this package.

apitte's People

Contributors

besir avatar borisvalo avatar czita avatar domm98cz avatar f3l1x avatar grossmannmartin avatar josefbenjac avatar kedlas avatar khorsky avatar kralmichal avatar lulco avatar mabar avatar martenb avatar martinmystikjonas avatar miranovy avatar paveljurasek avatar petrparolek avatar r-st avatar radimvaculik avatar rixafy avatar roman3349 avatar tg666 avatar to23mas avatar tomasvotruba avatar tonyvlcek avatar trejjam avatar vlastakozelka avatar vlczech avatar vody105 avatar woytam avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

apitte's Issues

Show better error message for non-matching number of RequestParameters

Hello,

the following code is missing request parameter id in @Path annotation, which is correctly reported. Unfortunatelly the error message doesn't say, where the problem exactly is (it's possible to find it in Tracy though).

/**
 * @API\Method("DELETE")
 * @API\Path("/")
 * @API\RequestParameters({
 *	@API\RequestParameter(name="id", type="string", description="ID of document to remove")
 * })
 */

Exception thrown:

Apitte\Core\Exception\Logical\InvalidStateException:
  Number of @RequestParameters (1) is bigger then mask parameters (0)

Improve routing - regular expressions

  • {id \d+}
  • {lang [a-z]{2}} - I'm not sure about syntax - regex uses {} characters for range. Should we use escaping or switch to <var>?
  • greediness? - some systems uses / in their identifiers - currently cannot be sent into apitte

Question is how matching should exactly act.
Route contains {id \d+}, so should string_id cause error like datatype is defined in @RequestParameter or should not match? (First variant is preferred by me)

Improve routing - routes order

If routes /foo/bar and /foo/{var} are defined then route /foo/bar should always match for /foo/bar url, no matter in which order are controllers registered. We should also check for collisions.

See also swagger docs

LinkGenerator

  • According to given id create a link to API endpoint.
  • Test a link generation with local php development server.
  • Maybe use nette/routing for internal router, it has constructUrl.

Output all error messages at once

Currently once a client error is found then it's immediatelly written to output.
We should e.g. validate all request parameters at once then output errors.
Validate whole request entity (and all request entities once #46 is implemented) then output errors.
Endpoints should behave the same.

Probably best would be an configurable exception, like $clientErrorException->addError($error).

Decorators improvements

  • split into 3 interfaces (RequestDecorator, ResponseDecorator, ErrorDecorator), drop decorator type tag in DI (only priority could be defined if needed)
  • if an error decorator return null then next in a row should be tried
  • request decorator accept only request
  • request and response decorators should be able to throw EarlyReturnResponseException (and error decorator maybe too?)

Request Interface

Hi there,

is there any way, how to get ApiRequest in Base Controller?

Kind Regards,

M.

withStatus() problem

    // not working
    $response->withStatus(404);
    return $response->writeJsonBody(['test']);

    // working
    $res = $response->withStatus(404);
    return $res->writeJsonBody(['test']);

    // working
    return $response->writeJsonBody(['test'])->withStatus(404);

Metadata for response

For cases like #96 - sending new auth tokens is common task

$response->withAdditionData('meta', ['foo' => 'bar']);

E.g. JsonUnifyTransformer would output

{
    "status": "success",
    "data": {},
    "errors": {},
    "meta": {
        "foo": "bar"
    }
}

Improve schema building

  • allow define same controller by all loaders (e.g. define in annotations and modify something in neon)
  • ArrayLoader
  • modify error messages to make sense for all loaders (currently are annotations-specific)
  • some tests
  • own loaders?
  • extend schema modifying options - middlewares and decorators should be able to describe what they do in openapi schema

ArraySerializator should check specific request parameters

Currently is during serialization checked only if method does not have more @RequestParameter(in=path) then parameters typed in its mask.

It should check if

  • every parameter in mask is also in path
  • every parameter in path is also in mask

Other request parameters are not checked

Improve entities

  • collections and nested entities support
    • in validations
    • in transformations (e.g. in CsvTransformer entities need to be flatten)
  • better document how RequestBody works
  • merge negotiations and responses??

Prefixed annotations does not work

Hi, I tried to import annotation namespace with Apitte\CoreAnnotation\Controller as API and then use for example @API\Controller() to avoid too long use list in all of my controllers.

This doesn't throw any error, it only returns nothing. If I use Apitte\CoreAnnotation\Controller\Controller() directly everything works fine.

It would also be nice to support this because it's similar to what we're all probably using right now with Doctrine (Doctrine\ORM\Mapping as ORM).

RequestParameterValidation

  • based on #35
  • extend existing RequestParameterValidation
  • check if every parameter in mask have also endpoint parameter (prevents weak-typed inputs)

how to CORS?

Hi Guys,

many thanks for your fantastic work!

I'm just wandering, what is the best approach to make "Apitte" available for Ajax POST. Not sure, how to handle responses for "OPTIONS" requests. Any idea? Any documentation? It will be maybe possible using some middleware, but I have no clue how to implement it.

Controller::setOpenApi() TypeError (array vs. string)

TypeError
Argument 1 passed to Apitte\Core\Schema\Builder\Controller\Controller::setOpenApi() must be of the type array, string given, called in P:\xampp\htdocs\vian_sensingapi\protected\vendor\apitte\core\src\DI\Loader\DoctrineAnnotationLoader.php on line 157
File: ...\Schema\Builder\Controller\Controller.php:149
146:        /**
147:         * @param mixed[] $openApi
148:         */
149:        public function setOpenApi(array $openApi): void
150:        {
151:            $this->openApi = $openApi;
152:        }
153:    

Commit 4bf882f was the last corect.

@AllowOptionsMethod annotation to handle OPTIONS when using CORS

Hi,
my current use case: JS app sends POST request and axios sends preflight OPTIONS request. So I have to annotate every class method, that handles POST with @Method({"POST", "OPTIONS"}) and in case it's OPTIONS request I send empty response like that:

    /**
     * @Path("/")
     * @Method({"POST", "OPTIONS"})
     */
    public function create(ApiRequest $request, ApiResponse $response)
    {
        if ($request->getMethod() === 'OPTIONS') {
            return $response;
        }
    }

I can imagine, that not all requests should be handled with CORS (not really sure, if there is any real use case), so it can be usefull to use @AllowOptionsMethod annotation that will send response to these requests automatically.

What do you think about it?

Tags with values (default null)

Controller->addTag does not have default value.
Method->addTag does not have value at all.

Note:

  • Add it to ArraySerializator.phpt

CheckAuth annotation for individual methods

Hi,

I'd like to add some kind of annotation for individual methods in the controllers to add ability to decide if the request needs authentication header or not - ideally in middleware.

Something like this

/**
 * @Controller
 * @ControllerPath("/")
 */
final class HomeController extends BaseV1Controller
{
	/**
	 * @Path("/")
         * @CheckAuth <---- SOMETHING LIKE THIS
	 * @Method("GET")
	 */
	public function index(ApiRequest $request, ApiResponse $response)
	{
		return $response->withEntity(ArrayEntity::from(['data' => ['Welcome']]));
	}
}

Question is, how can I check if this annotation exists in the middleware?

...or, is there any way how to add "CheckAuth" just for individual methods?

How to add additional data to the root of the response?

I'm using decorator to add some additional data into all responses...

class ResponseDecorator implements IResponseDecorator
{
    public function decorateResponse(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
    {
        $entity = $response->getEntity()->getData();
        $entity['somedata'] = ['id'=>1];

        return $response
            ->withHeader('Access-Control-Allow-Origin', '*')
            ->withHeader('Access-Control-Allow-Credentials', 'true')
            ->withHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, DELETE, PUT')
            ->withHeader('Access-Control-Allow-Headers', 'Authorization, Accept, Overwrite, Destination, Content-Type, Depth, User-Agent, Translate, Range, Content-Range, Timeout, X-Requested-With, If-Modified-Since, Cache-Control, Location')
            ->withHeader('Access-Control-Max-Age', 1728000)
            ->withEntity(ArrayEntity::from($entity));
    }

}

This returns all responses as following example:

{
    "status": "success",
    "data": {
        "test": "test",
        "somedata": {
            "id": 1
        }
    }
}

My question is if is there any way, how can I move "somedata" node to same level as "status" and "data" nodes.

Cheers

Improve error messages

  • RequestParameterValidation - invalid in, type - display list of constant values instead of link into EndpointParameter class

Disable controllers autowiring

There is no reason to autowire presenters as they are get internally from DI and no one should use controllers as dependencies in services

Nginx error - duplicate header 'Content-Type'

Řeőením je úprava funkce

	/**
	 * @param string $name
	 * @param array $values
	 * @return void
	 */
	protected function sendHeader($name, $values)
	{
		$name = str_replace('-', ' ', $name);
		$name = ucwords($name);
		$name = str_replace(' ', '-', $name);
		foreach ($values as $value) {
			header(sprintf('%s: %s', $name, $value), $name == "Content-Type");
		}
	}

Documentatation rewrite plans

  • endpoints
  • loaders
    • annotations
    • neon
  • other packages
  • decorators
  • dispatchers
  • request decorating (mappers, parameters, validators)
  • response decorating (mappers, negotiations, returns from endpoint)
  • usage with nette (api.php and index.php, each with own application class)
  • exceptions
    • how are handled and what is bonus of ClientErrorException and ServerErrorException
    • handling in negotiations, middlewares and own error handlers
  • architecture
    • how individual parts interact with each other
  • debug
  • request attributes
  • logging and handling errors

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.